赞
踩
- import java.util.HashMap;
- import java.util.Map;
- import java.util.stream.Collectors;
-
- public class Main {
- public static void main(String[] args) {
- // Create a HashMap to store the original key-value pairs
- Map<String, Object> originalMap = new HashMap<>();
- // Add some key-value pairs to the originalMap
- originalMap.put("key1", "Hello");
- originalMap.put("key2", 42);
- originalMap.put("key3", "World");
- originalMap.put("key4", 3.14);
-
- // Use Java Stream API to process the originalMap and create a new map
- Map<String, Object> newMap = originalMap.entrySet().stream()
- .collect(Collectors.toMap(
- // Keep the original key for each entry
- Map.Entry::getKey,
- // Lambda function to process each entry
- entry -> {
- // Get the value of the current entry
- Object value = entry.getValue();
- // Check if the value is an instance of String
- if (value instanceof String) {
- // Perform some operation for String type values (e.g., convert to uppercase)
- return ((String) value).toUpperCase();
- } else {
- // Perform some operation for non-String type values (e.g., convert to string and append "_converted")
- return value.toString() + "_converted";
- }
- }
- ));
-
- // Print the original and new maps to the console
- System.out.println("Original Map: " + originalMap);
- System.out.println("New Map: " + newMap);
- }
- }
使用entrySet()
方法返回一个包含键值对的Set集合,然后转Stream并对其执行操作,接着在收集器collect当中对map的value做不同的处理并返回
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。