2

I have the following data structure

public class Zones {

   private List<Zone> zones;
}

public class Zone {

  private int id;
  private String name;
  private List<Part> parts;
}

public class Part {
  private int id;
  private String name;
}

THis is my problem. I have with me an instance of Zones, say z.

I want to stream z and do the following: construct a map out of z with the following conditions: if the key (based on the "Id" of the Zone) is new, then create an entry in the map with the key and the Zone. If the key is a duplicate, then append all "parts" of this duplicate zone into the existing zone's parts list. In the end I should have a map with "Id" of the zone as the key and the zone as the value.

How can I do this in Java8 using streams?

1
  • If the key is a duplicate, then append all "parts" of this duplicate zone into the existing zone's parts list. ... what happens to the name in such a case for say z1 and z2 being Zone with the same id? Commented Mar 25, 2019 at 6:49

1 Answer 1

8

You can use Collectors.toMap(), to make a new Map with zone id as the key and Zone as the value, if there is a duplicate then take the List<Part> from the second Zone and append it to the first one:

  Map<Integer, Zone> map = z.getZones().stream()
                            .collect(Collectors.toMap(Zone::getId, Function.identity(), 
                             (zone1, zone2) -> {
                               zone1.getParts().addAll(zone2.getParts());
                               return zone1;
                             }));
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks Amardeep. While this helps to group by Id, what I need is to have the parts of the same zone merged so that I end up with one zone with aggregated parts in it's "parts" attribute. With the current approach, I end up with a key with 2 zone values whcih have the same zone Id.
@RamViswanathan yeah, I have updated my answer. Now you would have the Zones with the same zone Ids having merged Parts if there is an Id match between two zones.
Thanks Amardeep, this is exactly what I was looking for. Works like a charm!
how do i accept an answer ? It did solve my problem.
|

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.