user1781523
user1781523

Reputation:

Filtering data with a stream that consists of a list?

elementList is a list of all elements

class Element{  
   private ArrayList<Shape> shapeList = new ArrayList<Shape>();
}

...

class Shape{
   private String color;
   private String shape;
}

Trying to filter a list of elements, of which each contain a list of shapes that are all different.

    List<Shape> roundShapes = elementList.stream()  
            .filter(x -> x.getShapeList()(})    

 //not sure what to have here.
 //I need to loop/stream the data that i get form getShapeList(). How to do this?   
 //A stream inside a stream?

            .collect(Collectors.toList());

For example find a shape that is red and round. The problem is i cannot just filter it directly as the data is in within a another list.

I could for loop all the elements and add each shapeList into one big list, than stream that list. But that requires a for loop and iterating over each one, and I would like to use streams instead if for loops.

Upvotes: 0

Views: 101

Answers (2)

LivewareError
LivewareError

Reputation: 23

Are you saying that you want to end up with a list of Shape objects collected from your Element objects and filtered based on some predicate, for example, red and round? If so, you could try flat - mapping the stream of Element objects to their Shape lists, and then filtering, like so:

<List<Shapes> roundShapes = elementList.stream()
                            .flatMap(x -> x.getShapes().stream())
                            .filter(x -> (x.getColor().equals("red") && x.getShape().equals("round")))
                            .collect(Collectors.toList());

Upvotes: 0

Kishore Bandi
Kishore Bandi

Reputation: 5701

You need to flatten the map and then iterate over the shapes.
Replace the shape.getShape().equals("Round") with the filter criteria on shapes that you want.

List<Shapes> roundShapes = elementList.stream().flatMap(element -> element.getShapeList().stream())
                    .filter(shape -> shape.getShape().equals("Round")).collect(Collectors.toList());

Upvotes: 1

Related Questions