Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 map filter and sort

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?

like image 836
Caal Saal VI Avatar asked Aug 30 '17 02:08

Caal Saal VI


2 Answers

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", "");
like image 144
shmosel Avatar answered Oct 27 '22 15:10

shmosel


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());
like image 21
Misha Avatar answered Oct 27 '22 17:10

Misha