Java 8 filter for contains
Solution 1
You'll need to use cityList.stream()
rather than Stream.of(cityList)
. Reason being that currently, Stream.of(cityList)
returns a Stream<List<String>>
whereas you want Stream<String>
. You can still accomplish your task by using your current approach but you'll need to flatten the Stream<List<String>>
into Stream<String>
(I do not recommend as it causes un-necessary overhead hence it's better to use cityList.stream()
).
That said, here is how you should go about accomplishing your task:
System.out.println(cityList.stream().filter(str -> str.contains("a")).collect(Collectors.toList()));
Solution 2
Stream.of(cityList)
creates a Stream<List<String>>
having a single element - your input List
.
You need to use cityList.stream()
in order to get a Stream<String>
contaning the elements of your input List
.
System.out.println(cityList.stream().filter(str -> str.contains("a")).collect(Collectors.toList()));
outputs
[Noida, Gurgaon, Utah]
The only reason you code passed compilation is that both List
and String
have a contains
method that returns a boolean
.
Ashish
Having good hands in Mulesoft, Apigee, Microservices and Spring Boot.
Updated on July 22, 2022Comments
-
Ashish almost 2 years
I am new to Java 8 and when I am trying to put a filter for all those cities which contains one letter. It doesn't work for me. However, when I run it with old approach it works.
List<String> cityList = new ArrayList<>(); cityList.add("Noida"); cityList.add("Gurgaon"); cityList.add("Denver"); cityList.add("London"); cityList.add("Utah"); cityList.add("New Delhi"); System.out.println(cityList); /* Prior to Java 8 Approach */ for (String city : cityList) { if(city.contains("a")){ System.out.println(city + " contains letter a"); } } /* Java 8 Approach */ System.out.println(Stream.of(cityList).filter(str -> str.contains("a")).collect(Collectors.toList()));
Here is the output
Noida contains letter a Gurgaon contains letter a Utah contains letter a []
Can you please explain me where am I am making mistakes.
Thanks in advance !