Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

collections - Convert List<List<Object>> to Map<Object,List<Object>> Java8

I have a Object

class Wrapper{ 
   private SomeObject someObject;
   private String value;
}

class SomeObject{
  private String id;
}

I have function that returns List<List<Wrapper>> I want to convert it to Map<SomeObject,List<Wrapper>>

At the moment I'm using looping and compare to to achieve this. Is there way to achieve this via Java8 streams

wrappers.stream()
            .flatMap(w -> w.stream()) //stream of wrapper
            .collect(Collectors.toMap(<not sure which mapping fucntion to use here>))
question from:https://stackoverflow.com/questions/65846405/convert-listlistobject-to-mapobject-listobject-java8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use groupingBy collector along with the flatMap operator to get this done. Here's how it looks.

Map<SomeObject, List<Wrapper>> map = l.stream().flatMap(List::stream)
    .collect(Collectors.groupingBy(Wrapper::getSomeObject));

However, an iterative version would be much readable and faster than streams.

Map<SomeObject, List<Wrapper>> m = new HashMap<>();
for (List<Wrapper> wrappers : l)
    for (Wrapper w : wrappers)
        m.computeIfAbsent(w.someObject, unused -> new ArrayList<Wrapper>()).add(w);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...