Distinct elements in collection

This example will find the unique values or elements in a collection. The default behavior of set is that that it cannot contain duplicate elements and it should be used where applicable. In some cases you don't have a luxury of working with a collection of the the Set interface so you may need to use methods below to find the distinct elements.

Java 8

Distinct numbers

The distinct number example is using the IntStream but it can be subsituted with DoubleStream or LongStream.

@Test
public void distinct_elements_java8_numbers () {
    
    List<Integer> distinctIntegers = IntStream.of(5, 6, 6, 6, 3, 2, 2)
        .distinct()
        .boxed()
        .collect(Collectors.toList());
    
    logger.info(distinctIntegers);
    
    assertEquals(4, distinctIntegers.size());
    assertThat(distinctIntegers, contains(
            5, 6, 3, 2));
}

Distinct strings

@Test
public void distinct_elements_java8_objects () {

    List<String> objects = new ArrayList<>();
    objects.add("Hello");
    objects.add("Hello");
    objects.add("World");
    objects.add("Good morning");

    List<String> distinctObjects = objects.stream().distinct()
            .collect(Collectors.toList());
    
    logger.info(distinctObjects);
    
    assertEquals(3, distinctObjects.size());
    assertThat(distinctObjects, contains(
            "Hello", "World", "Good morning"));
}

Google Guava

@Test
public void distinct_elements_guava_objects () {
    
    List<Integer> integers = Lists.newArrayList(5, 6, 6, 6, 3, 2, 2);
    
    ImmutableSet<Integer> distinctIntegers = ImmutableSet.copyOf(integers);
    
    logger.info(distinctIntegers);
    
    assertEquals(4, distinctIntegers.size());
    assertThat(distinctIntegers, contains(
            5, 6, 3, 2));
}