Ádám Bozzay
Ádám Bozzay

Reputation: 609

Java 8 stream reduce Map

I have a LinkedHashMap which contains multiple entries. I'd like to reduce the multiple entries to a single one in the first step, and than map that to a single String. For example: I'm starting with a Map like this:

{"<a>"="</a>", "<b>"="</b>", "<c>"="</c>", "<d>"="</d>"}

And finally I want to get a String like this:

<a><b><c><d></d></c></b></a>

(In that case the String contains the keys in order, than the values in reverse order. But that doesn't really matter, I'd like an general solution)

I think I need map.entrySet().stream().reduce(), but I have no idea what to write in the reduce method, and how to continue.

Upvotes: 2

Views: 4961

Answers (2)

gdejohn
gdejohn

Reputation: 7579

Since you're reducing entries by concatenating keys with keys and values with values, the identity you're looking for is an entry with empty strings for both key and value.

String reduceEntries(LinkedHashMap<String, String> map) {
    Entry<String, String> entry =
        map.entrySet()
           .stream()
           .reduce(
               new SimpleImmutableEntry<>("", ""),
               (left, right) ->
                   new SimpleImmutableEntry<>(
                       left.getKey() + right.getKey(),
                       right.getValue() + left.getValue()
                   )
           );
    return entry.getKey() + entry.getValue();
}

Java 9 adds a static method Map.entry(key, value) for creating immutable entries.

Upvotes: 5

Paul Lemarchand
Paul Lemarchand

Reputation: 2096

here is an example about how I would do it :

import java.util.LinkedHashMap;

public class Main {

    static String result = "";

    public static void main(String [] args)
    {
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("<a>", "</a>");
        map.put("<b>", "</b>");
        map.put("<c>", "</c>");
        map.put("<d>", "</d>");

        map.keySet().forEach(s -> result += s);
        map.values().forEach(s -> result += s);

        System.out.println(result);
    }
}

note: you can reverse values() to get d first with ArrayUtils.reverse()

Upvotes: 0

Related Questions