How to filter element or null from an Array of objects in Java


I have an array of Objects, I need to find out an element. Either I get one element or none in my operation.
Is it possible to do this in one line in Java?

1 Answer

4 years ago by

Using Java's streams combining with findAny, orElse(null) you can do this operation in single line.
Following code shows you how to do that.

String idToFilter = "u2";
User user = users.stream()
                         .filter(u -> u.id.equals(idToFilter))
                         .findAny()
                         .orElse(null);

Following is the full example

import java.util.*;

public class HelloWorld {
    public static void main(String[] args) {
      
        List<User> users = new ArrayList<>();
        users.add(new User("u1", "Foo", 21));
        users.add(new User("u2", "Bar", 27));
        users.add(new User("u3", "Yar", 28));
        
        String idToFilter = "u2";
        
        User user = users.stream()
                         .filter(u -> u.id.equals(idToFilter))
                         .findAny()
                         .orElse(null);
                         
        System.out.println("user: " + user);
    }
}


class User {
  public User(String id, String name, int age){
      this.id = id;
      this.name = name;
      this.age = age;
  }
  
  String id;
  String name;
  int age;
  
  @Override
  public String toString(){
    return "id: " + id + ", name: " + name + ", age: " + age;
  }
}

You can execute the code and see the results here https://onecompiler.com/java/3vy4s4pcv

4 years ago by Karthik Divi