Filter and sort by Java 8

I want to port 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"); } 

The correct conclusion:

 FrontMiddleBack 

I tried using streamset -> stream, but it does not return in the 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 

Is it possible to get the same result using Java 8?

+5
source share
2 answers

You can transfer the desired values ​​and attached values:

 String title = Stream.of("prefix", "name", "postfix") .filter(data::containsKey) .map(data::get) .collect(joining()); 
+5
source

The threads here are a bit crowded, IMO. But you can still use Java 8 to your advantage, Map.getOrDefault() :

 String title = data.getOrDefault("prefix", "") + data.getOrDefault("name", "") + data.getOrDefault("postfix", ""); 
+9
source

Source: https://habr.com/ru/post/1271355/


All Articles