Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the size of a Stream after applying a filter by lambda expression?

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?

like image 789
Abdennour TOUMI Avatar asked Mar 14 '15 12:03

Abdennour TOUMI


People also ask

How do you use the filter method in streams?

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.

What is stream in lambda expression?

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.

How do you filter a stream string?

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.

How do I count a stream in Java?

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).


1 Answers

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)).

like image 156
Alexis C. Avatar answered Sep 20 '22 21:09

Alexis C.