Consider the following code:
List<Locale> locales = Arrays.asList( new Locale("en", "US"), new Locale("ar"), new Locale("en", "GB") ); locales.stream().filter(l -> l.getLanguage() == "en");
How do I get the size of the locales
ArrayList
after applying filter
, given that locales.size()
gives me the size before applying filter
?
The filter() function of the Java stream allows you to narrow down the stream's items based on a criterion. If you only want items that are even on your list, you can use the filter method to do this. This method accepts a predicate as an input and returns a list of elements that are the results of that predicate.
Lambda expressions are much like anonymous functions. Streams are sequences or elements that support sequential or parallel operations on their items (in a very different way from classic collections). Functional programming is a paradigm that favors stateless operations and avoids modifications to the program state.
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.
Stream count() method in Java with exampleslong count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation).
When you get a stream from the list, it doesn't modify the list. If you want to get the size of the stream after the filtering, you call count()
on it.
long sizeAfterFilter = locales.stream().filter(l -> l.getLanguage().equals("en")).count();
If you want to get a new list, just call .collect(toList())
on the resulting stream. If you are not worried about modifying the list in place, you can simply use removeIf
on the List
.
locales.removeIf(l -> !l.getLanguage().equals("en"));
Note that Arrays.asList
returns a fixed-size list so it'll throw an exception but you can wrap it in an ArrayList
, or simply collect the content of the filtered stream in a List
(resp. ArrayList
) using Collectors.toList()
(resp. Collectors.toCollection(ArrayList::new)
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With