Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Collection<Pair<K, Collection<V>> to a List<MyObject<K,V>> using Java stream API?

Tags:

java

lambda

My traditional code would look like this:

List<MyObject> transform(Collection<java.util.Map.Entry<String, List<String>>> input) {
    List<MyObject> output = new LinkedList<>();
    for (Entry<String, List<String>> pair : input) {
        for (String value : pair.getValue()) {
            output.add(new MyObject(pair.getKey(), value));
        }
    }
    return output;
}

Can I do the same with lambda expressions? I’ve tried around, but I don’t get it. The outer collection is unsorted, but the List<String> is sorted. The result objects may return in the result list without any order, with the exception that objects created from the same key String should follow each other to preserve the order of the value. Is this at all possible?

like image 829
Matthias Ronge Avatar asked Feb 17 '26 10:02

Matthias Ronge


1 Answers

input.stream()
     .flatMap(e -> e.getValue()
                    .stream()
                    .map(v -> new MyObject(e.getKey(), v)))
     .collect(Collectors.toCollection(LinkedList::new));
like image 70
Lukas Eder Avatar answered Feb 21 '26 13:02

Lukas Eder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!