Friday, 6 May 2016

Remove duplicates in Java 8 using Stream.distinct()

Remove duplicates from a list using Stream.distinct() in Java 8

In Java 8 we can easily remove duplicates from a List(or collection) in the following manner.

File:RemoveDuplicateUsingStream .java

package net.codermag.java8;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class RemoveDuplicateUsingStream {
 public static void main(String[] args) {
    List<Integer> integerList = Arrays.asList(67, 8, 4, 21, 25, 64, 76, 52, 4, 21);   
    
    Stream<Integer> filteredStream=integerList.stream().distinct();
     
    
    
    System.out.println("Count before removing duplicates : "+integerList.size());
    System.out.println("Count after removing duplicates : "+filteredStream.count());
    
   }
}



Output:

Count before removing duplicates : 10
Count after removing duplicates : 8