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?
Streams are a little overkill here, IMO. But you can still use Java 8 to your advantage, with Map.getOrDefault()
:
String title = data.getOrDefault("prefix", "")
+ data.getOrDefault("name", "")
+ data.getOrDefault("postfix", "");
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With