行业知识
【Java】使用Stream API处理Map并返回新的Map
2026-12-01 02:14:00
来源:互联网转载
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 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 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做不同的处理并返回
()点赞,你的认可是我创作的动力 !
收藏,你的青睐是我努力的方向!
()✏️评论,你的意见是我进步的财富!
上一篇:服务器网卡被禁用怎么恢复?
下一篇:苹果怎么选服务器设置?