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 !
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()));
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