Search code examples
javalambdajava-stream

Convert nested for loop to stream in java 11


Convert to Streams:

private static List<Location> extractLocation(List<Location> locations){
        List<Location> locationList = new ArrayList<>();
        for(Location l : locations){
            if(l!=null){
                final Location location = Location.builder()
                        .id(l.getId())
                        .build();
                for(Address address: l.getAddresses()){
                    if(address.getType().equals("primary")){
                        location.setPrimaryAddress(address);
                    }
                    else{
                        location.setBillingAddress(address);
                    }
                }
                locationList.add(location);
            }
        }
        return locationList;
    }

I am stuck after building the object. For the nested loop, since it is next step after the Location object is built, which Stream method to apply here to set primary and billing address.

private static List<Location> extractLocationStream(List<Location> locations){
        return locations.stream()
                .filter(location -> location!=null)
                .map(location ->
                {
                    Location l = Location.builder()
                        .id(location.getId())
                        .build();
                    location.getAddresses().stream()
                            .filter(address -> address.getType().equals("primary")).// what to do now
                })

                .collect(Collectors.toList());
    }

Location and Address classes:

@Data
@AllArgsConstructor
class Address{
    private int id;
    private String type;
}

@Data
@AllArgsConstructor
@Builder
class Location{
    private int id;
    private List<Address> addresses;
    private Address primaryAddress;
    private Address billingAddress;

}

Solution

  • How about this:

        private static List<Location> extractLocationStream(List<Location> locations) {
            return locations.stream().filter(location -> location != null).map(location -> {
                Location l = Location.builder().id(location.getId()).build();
                location.getAddresses()/*.stream()*/.forEach(address -> { // Here, stream is optional
                    if ("primary".equals(address.getType())) {
                        l.setPrimaryAddress(address); //Overwrites if multiple primary
                    } else {
                        l.setBillingAddress(address); //Overwrites if multiple non-primary
                    }
                });
                return l;
            }).collect(Collectors.toList());
        }