【问题标题】:How to use stream in Java to process the Map [duplicate]如何在Java中使用流来处理地图[重复]
【发布时间】:2021-05-27 15:57:49
【问题描述】:

我正在使用 Java 应用程序。

这是我的地图

{
    "name": "John",
    "address": "US"
}

代码块:

Map<String, Object> response = new HashMap<>();

final List<String> TYPES = List.of("name", "gender", "age");

String display = "text"; // text, password

for (Map.Entry<String, Object> entry : map.entrySet()) {
    if (TYPES.contains(entry.getKey())) {
        String result = (String) entry.getValue();

        if (display.equals("text"))) {
           result = // do some manipulation
        } else if (display.equals("password")) {
            result = // do some manipulation
        }

        response.put(entry.getKey(), result);
    } else {
        response.put(entry.getKey(), entry.getValue());
    }
}

根据显示类型,我得到不同的响应。上面的代码工作正常。使用 Java Streams 执行此代码是否更有效?

【问题讨论】:

  • String display = text; // text, password 是什么意思? text 是变量还是您忘记将 text 放在引号中的错字?
  • @daniu text 是一个封闭的字符串。
  • 那你就不用查询下面的display.equals(...)了吧?
  • @daniu 我需要等于条件来改变结果的值
  • 但是在你的代码中,display.equals("text") 将永远被执行,而display.equals("password") 永远不会。所以要么你传入display 值,要么你可以去掉那个if/else。

标签: java hashmap java-stream


【解决方案1】:

试试这个:

map.entrySet().stream()
              .filter(x ->TYPES.contains(x.getKey())
              .collect(Collectors.toMap(x -> x.getKey(), p -> (x.getValue().equals("text") || x.getValue().equals("display"))? "some_manipolation" : x.getValue())) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-28
    • 2019-08-17
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    相关资源
    最近更新 更多