Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 filter for contains

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 !

like image 694
Ashish Avatar asked Jan 29 '23 15:01

Ashish


1 Answers

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()));
like image 83
Ousmane D. Avatar answered Feb 02 '23 09:02

Ousmane D.