0

I have this POJO. Also, I have a List of Students and I want to filter with stream which registers have in his schoolname the text santa. In SQL it would be something like this: LIKE %SANTA%

  public class Student {
    private String name;
    private String lastName;
    private String city;
    private String schoolname;
    private String telephone;

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public String getLastName() {
      return lastName;
    }

    public void setLastName(String lastName) {
      this.lastName = lastName;
    }

    public String getCity() {
      return city;
    }

    public void setCity(String city) {
      this.city = city;
    }

    public String getSchoolname() {
      return schoolname;
    }

    public void setSchoolname(String schoolname) {
      this.schoolname = schoolname;
    }

    public String getTelephone() {
      return telephone;
    }

    public void setTelephone(String telephone) {
       this.telephone = telephone;
    }
}

And I would like to obtain the students which his schoolname contains the string santa, do you know how can I have to do the filter with streams?

I need to do with stream, I can't do it with if and else statements.

Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
fmd89
  • 17
  • 2
  • Have you tried to do something with streams? – Kayaman Mar 19 '20 at 10:53
  • you can use `filter()` with a Regex `match()`. – Fureeish Mar 19 '20 at 10:53
  • 1
    Does this answer your question? [What is the best way to filter a Java Collection?](https://stackoverflow.com/questions/122105/what-is-the-best-way-to-filter-a-java-collection) – Smile Mar 19 '20 at 10:57
  • If you need a tutorial with text and video, here it is - http://tutorials.jenkov.com/java-functional-programming/streams.html – MasterJoe Mar 19 '20 at 15:44

2 Answers2

1

Stream over the List and apply a filter() that checks whether the school name of a Student contains "SANTA".

List<School> input = ...
List<School> output = 
    input.stream()
         .filter(s -> s.getSchoolname().contains("SANTA"))
         .collect(Collectors.toList());

If you want this filter not to be case sensitive, you can write

.filter(s -> s.getSchoolname().toUpperCase().contains("SANTA"))

If you want both the List that contains "SANTA" and the List that doesn't contain it, you can use Collectors.partitioningBy():

List<School> input = ...
Map<Boolean,List<School>> output = 
    input.stream()
         .collect(Collectors.partitioningBy(s -> s.getSchoolname().contains("SANTA")));
Eran
  • 387,369
  • 54
  • 702
  • 768
1

You can use stream() and filter() where students is list of Student object.

students.stream().filter(student->student.getSchoolname().contains("santa")).collect(Collectors.toList());
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24