Streams – distinct() operation

Stream distinct() operation in Java is an intermediate operation, and it returns a stream with unique elements.

It is useful when we need to remove duplicate elements from the collection.

The distinct() operation calls the equals() and hashCode() methods, so elements of the Stream need to belong to a class that overrides them.

Java Stream distinct() operation – examples

Example 1:

Create a program that takes a list of strings and removes all duplicate elements:

class Test {

  public static void main(String[] args) {
    List<String> names = new ArrayList<>(Arrays.asList("Megan", "John", "Melissa", "Tom", "John", "Megan", "Steve", "Tom"));

    List<String> uniqueNames = names.stream()
            .distinct()
            .collect(Collectors.toList());

    System.out.println(uniqueNames);
  }
}

Output: [Megan, John, Melissa, Tom, Steve]


Example 2:

Let’s create a custom User class:

class User {
  private String name;
  private String username;
  private String membershipType;
  private String address;

  public User(String name, String username, String membershipType, String address) {
    this.name = name;
    this.username = username;
    this.membershipType = membershipType;
    this.address = address;
  }

  @Override
  public String toString() {
    return "user: {" + name + " " + username + " " + membershipType + address + "} ";
  }
}


Now, let’s create a program that will take a list of users and return a list of unique elements:

class Test {

  public static void main(String[] args) {
    List<User> uniqueUsers = getAllUsers().stream()
            .distinct()
            .collect(Collectors.toList());

    System.out.println(uniqueUsers);
  }

  private static List<User> getAllUsers() {
    List<User> users = new ArrayList<>();
    users.add(new User("John", "john123", "premium", "5th Avenue"));
    users.add(new User("Megan", "meganusr", "gold", "New Light Street"));
    users.add(new User("John", "john123", "premium", "5th Avenue"));
    users.add(new User("Melissa", "mellisa1", "premium", "Ser Kingston Street"));

    return users;
  }
}

Output: [user: {John john123 premium5th Avenue} , user: {Megan meganusr goldNew Light Street} , user: {John john123 premium5th Avenue} , user: {Melissa mellisa1 premiumSer Kingston Street} ]


You see that a duplicate element is not removed from the list. It’s because we didn’t implement the equals() and hashCode() methods in the User class. Let’s add it now and execute the above program again:

class User {
  private String name;
  private String username;
  private String membershipType;
  private String address;

  public User(String name, String username, String membershipType, String address) {
    this.name = name;
    this.username = username;
    this.membershipType = membershipType;
    this.address = address;
  }

  @Override
  public String toString() {
    return "user: {" + name + " " + username + " " + membershipType + address + "} ";
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof User)) return false;
    User user = (User) o;
    return Objects.equals(name, user.name) && Objects.equals(username, user.username) && Objects.equals(membershipType, user.membershipType) && Objects.equals(address, user.address);
  }

  @Override
  public int hashCode() {
    return Objects.hash(name, username, membershipType, address);
  }
}

class Test {

  public static void main(String[] args) {
    List<User> uniqueUsers = getAllUsers().stream()
            .distinct()
            .collect(Collectors.toList());

    System.out.println(uniqueUsers);
  }

  private static List<User> getAllUsers() {
    List<User> users = new ArrayList<>();
    users.add(new User("John", "john123", "premium", "5th Avenue"));
    users.add(new User("Megan", "meganusr", "gold", "New Light Street"));
    users.add(new User("John", "john123", "premium", "5th Avenue"));
    users.add(new User("Melissa", "mellisa1", "premium", "Ser Kingston Street"));

    return users;
  }
}

Output: [user: {John john123 premium5th Avenue} , user: {Megan meganusr goldNew Light Street} , user: {Melissa mellisa1 premiumSer Kingston Street} ]


That’s it!

 

Leave a Reply

Your email address will not be published.