Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Streams - Apply fixed amount of predicate filters to single Stream

Is there a way to apply fixed amount of Predicates to an opened Stream ? I really can't get any attempt of mine to work. Either the attempt ends up with stream closed error or not all filters are applied.

Example:

 // list of all JLabels of any container
private final List<JLabel> listOfLabels = new ArrayList<>();
// set of user-defined filters
private final Set<Predicate<JLabel>> filters = new HashSet<>();

// let's add some filters
filters.add(label -> label.getBackground() == Color.RED);
filters.add(label -> label.getWidth() > 500);

How can I apply all filter to the Stream of listOfFiles ? Let's say we want to hide JLabels NOT matching these filters. I am looking for something like a non-working code snippet below.

public void applyFilters() {
   listOfLabels.forEach(label -> label.setVisible(false)); // hide all labels
   Stream<JLabel> stream = listOfLabels.stream();
   filters.forEach(stream::filter);
   stream.forEach(label -> label.setVisible(true));
   // stream closed error
}

After method applyFilters() is executed, the container should have visible only labels matching all predicates defined by filters set. (red background and width greater than 500 in this example).

like image 448
glf4k Avatar asked Mar 08 '23 15:03

glf4k


1 Answers

When you work with Stream you have to always use the link to Stream object that was return by applying previous operation. As you can see from the API:

Stream<T> filter(Predicate<? super T> predicate);

The Stream object is returned and javadoc says:

Returns a stream consisting of the elements of this stream that match * the given predicate.

Having this in mind, in your case, we can apply something like the following:

Convert:

filters.forEach(stream::filter);

To:

   for (Predicate<JLabel> filter : filters) {
        stream = stream.filter(filter);
   }

That should work, since now you update the link to the Stream object and follow documentation.

like image 100
dvelopp Avatar answered Apr 30 '23 15:04

dvelopp