Home > Mobile >  Build map from list by lambda
Build map from list by lambda

Time:11-25

I have a Group model with an inner field List<Entity> entities

How is possible to change the below code to one line by lambda and stream

 Map<String, String> entityGroup = new HashMap<>();
 groups.forEach(g -> g.getEntities()
                .forEach(e -> entityGroup.put(e.getKey(), g.getKey()))
 );

Each entity in the inner list should be the key in the map and the value should be the Group itself

Thanks

CodePudding user response:

To do this using streams, you would need to make a stream of map-entries and then collect it into a Map.

I'm using Map.entry in my example, which is available in Java 9 and up. If you're on Java 8, you can use AbstractMap.SimpleEntry or some other kind of Pair-class.

Something like this:

Map<String, String> entityGroup = groups.stream()
    .flatMap(group -> group.getEntities().stream()
        .map(entity -> Map.entry(entity.getKey(), group.getKey())))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

CodePudding user response:

Here's a runnable example which doesn't require you to explicitly create a new entry like the solution above:

import java.util.*;
import java.util.stream.*;

public class MyClass {
    public static void main(String args[]) {
        List<B> b1 = List.of(new B("a", "1"), new B("b", "2"));
        List<B> b2 = List.of(new B("x", "3"), new B("y", "4"));
        A a1 = new A(b1);
        A a2 = new A(b2);
        List<A> allAs = List.of(a1, a2);
        Map<String, String> map =
               allAs.stream().flatMap(a -> a.vals.stream())
               .collect(Collectors.toMap(B::getKey, B::getValue));
        System.out.println(map); // {a=1, b=2, x=3, y=4}
    }
}

class A {
    List<B> vals;
    public A(List<B> vals) { this.vals = vals; }
}

class B {
    String k, v;
    public B(String k, String v) { this.k = k; this.v = v; }
    public String getKey() { return this.k; }
    public String getValue() { return this.v; }
}
  •  Tags:  
  • java
  • Related