当前位置:   article > 正文

【Java】使用Stream API处理Map并返回新的Map_java stream 返回map

java stream 返回map
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.stream.Collectors;
  4. public class Main {
  5. public static void main(String[] args) {
  6. // Create a HashMap to store the original key-value pairs
  7. Map<String, Object> originalMap = new HashMap<>();
  8. // Add some key-value pairs to the originalMap
  9. originalMap.put("key1", "Hello");
  10. originalMap.put("key2", 42);
  11. originalMap.put("key3", "World");
  12. originalMap.put("key4", 3.14);
  13. // Use Java Stream API to process the originalMap and create a new map
  14. Map<String, Object> newMap = originalMap.entrySet().stream()
  15. .collect(Collectors.toMap(
  16. // Keep the original key for each entry
  17. Map.Entry::getKey,
  18. // Lambda function to process each entry
  19. entry -> {
  20. // Get the value of the current entry
  21. Object value = entry.getValue();
  22. // Check if the value is an instance of String
  23. if (value instanceof String) {
  24. // Perform some operation for String type values (e.g., convert to uppercase)
  25. return ((String) value).toUpperCase();
  26. } else {
  27. // Perform some operation for non-String type values (e.g., convert to string and append "_converted")
  28. return value.toString() + "_converted";
  29. }
  30. }
  31. ));
  32. // Print the original and new maps to the console
  33. System.out.println("Original Map: " + originalMap);
  34. System.out.println("New Map: " + newMap);
  35. }
  36. }

使用entrySet()方法返回一个包含键值对的Set集合,然后转Stream并对其执行操作,接着在收集器collect当中对map的value做不同的处理并返回 


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/495175
推荐阅读
相关标签