Caal Saal VI :
I want to migrate this example to Java 8:
Map<String, String> data = new HashMap<String, String>() {{
put("name", "Middle");
put("prefix", "Front");
put("postfix", "Back");
}};
String title = "";
if (data.containsKey("prefix")) {
title += data.get("prefix");
}
if (data.containsKey("name")) {
title += data.get("name");
}
if (data.containsKey("postfix")) {
title += data.get("postfix");
}
Correct output:
FrontMiddleBack
I tried with entryset -> stream but it doesn't return in correct order.
String titles = macroParams.entrySet().stream()
.filter(map -> "name".equals(map.getKey()) || "postfix".equals(map.getKey()) || "prefix".equals(map.getKey()))
.sorted()
.map(Map.Entry::getValue)
.collect(Collectors.joining());
Output:
MidleFrontBack
Can I get the same result using Java 8?
Misha :
You can stream over the desired keys and join values that are present:
String title = Stream.of("prefix", "name", "postfix")
.filter(data::containsKey)
.map(data::get)
.collect(joining());
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=472613&siteId=1