找到你要的答案

Q:Java 8 Lambda Map

Q:java 8λ地图

Java 8 Lambda Map for each create a new object and add this new objet in a list

This is my firts step

Map<Integer, List<Obj>> objGroupBy = list.stream().collect(Collectors.groupingBy(Obj::getSomething)); 


List<Obj2> lst2= new ArrayList<Obj2>();

for (Entry<Integer, List<Obj>> entry : objGroupBy .entrySet())
{
    lst2.add(new Obj2(entry.getKey().intValue(), entry.getValue()));
}

I want to know if it possible to do it in lambda Thanks!

java 8λ地图 for each create a new object and add this new objet in a list

这是我的第一步

Map<Integer, List<Obj>> objGroupBy = list.stream().collect(Collectors.groupingBy(Obj::getSomething)); 


List<Obj2> lst2= new ArrayList<Obj2>();

for (Entry<Integer, List<Obj>> entry : objGroupBy .entrySet())
{
    lst2.add(new Obj2(entry.getKey().intValue(), entry.getValue()));
}

I want to know if it possible to do it in lambda Thanks!

answer1: 回答1:

Equivalent to your code:

List<Obj2> lst2 = list.stream()
                      .map(o -> new Obj2(o.getSomething(), o))
                      .collect(Collectors.toList());

Now if you really want to start the same way:

List<Obj2> lst2 = list.stream()
                      .collect(Collectors.groupingBy(Obj::getSomething))
                      .entrySet()
                      .stream()
                      .map(e -> new Obj2(e.getKey(), e.getValue()))
                      .collect(Collectors.toList());

相当于你的代码:

List<Obj2> lst2 = list.stream()
                      .map(o -> new Obj2(o.getSomething(), o))
                      .collect(Collectors.toList());

现在,如果你真的想开始相同的方式:

List<Obj2> lst2 = list.stream()
                      .collect(Collectors.groupingBy(Obj::getSomething))
                      .entrySet()
                      .stream()
                      .map(e -> new Obj2(e.getKey(), e.getValue()))
                      .collect(Collectors.toList());
java  lambda