【发布时间】: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