Java 8 lambda expression for finding "contains"

10,195

Do you mean this:

.filter(user -> locations.contains(user.getLocation())
Share:
10,195
Ole V.V.
Author by

Ole V.V.

Java programmer. Amateur musician, harpsichord, good. Two kids, 9 and 11 years old as of writing. He, him (Ole, sir, …). My comments on Stack Overflow: I know I'm chatty. I try to delete outdated comments, but I am no doubt missing some. Please feel free to flag as "no longer needed". My answers: I am no longer contributing answers to Stack Overflow. Why not? Information that I considered essential was mistaken for fluff and was deleted from more than 50 of my answers by a user and at least two moderators. It's not a game I can see myself taking part in. Writing answers was fun for 6 years. It isn't anymore.

Updated on June 04, 2022

Comments

  • Ole V.V.
    Ole V.V. almost 2 years

    I have a method that takes List<String> locations as a parameter. I am populating a list of users in the same method based on a particular condition. Now what I want is, the user should be present in this locations. In short, the user is valid iff user's location is present in the list of locations provided. locations.

    This is my current code:

    primaryList.stream()
            .filter(some_pattern_matching)[.MATCH THE LOCATION HERE]
            .map(user -> user.getNames())
            .collect(toList())
    

    is there any way to say locations.contains(user -> user.getLocation()) OR user -> user.getLocation().isPresentIn(locations) OR have locations converted into one more stream and then do matching?

    This is my current code:

     .filter(locations.stream().filter(loc -> loc.equalsIgnoreCase(s.getLocation())))
    

    which of course does not compile.

    • Tomasz Bawor
      Tomasz Bawor almost 7 years
      Could you provide some minimal working example of your code?
    • JB Nizet
      JB Nizet almost 7 years
      the user is valid iff user's location is present in the list of locations provided: so, boolean userIsValid = locations.contains(user.getLocation())? Is that what you want? If not, provide the method you want to implement, with its arguments, return type, and javadoc, because it's quite unclear.
  • Satish Patro
    Satish Patro over 3 years
    This is case senstive. What he is doing is case senstive check