0

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!

3
  • 2
    Why don't you try it yourself? Commented Jun 23, 2015 at 15:51
  • You really think I don't try lol! Commented Jun 23, 2015 at 17:24
  • What other explanation is there to it? Commented Jun 23, 2015 at 18:32

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.