How to Get Unique Values from ArrayList using Java 8?


By taking advantage of Java 8 functional programming features like the Stream API and streams and lambda expressions, extracting unique values from an ArrayList becomes simpler and quicker. Leveraging these capabilities you can extract distinct elements without tedious iterations or manual checks; lambda expressions allow concise yet readable code which makes this task even simpler. Whether dealing with large datasets or simply eliminating duplicates Java 8 offers powerful yet elegant solutions for retrieving unique values from an ArrayList.

ArrayList

Java's ArrayList class implements the List interface, providing dynamic array-like functionality for storage and manipulation of collections of elements within an adjustable array. As elements are added or removed from ArrayList's arrays, its size automatically adapts, offering flexibility and convenience.

A variety of methods exist within an ArrayList to access, modify, add and remove elements. Elements may be accessed with get() and modified with set() respectively; additionally they can be added or removed at specific positions within or at the end of a list using add or remove at certain positions respectively.

ArrayList<String> names = new ArrayList<>();

Approaches

Java 8 offers several approaches for finding unique values within an arrayList. Below are two frequently employed strategies.

  • Using Stream and distinct()

  • Using HashSet

Both methods provide an efficient method to extract unique values from an ArrayList using Java 8 features, so simply choose one that best meets your requirements and coding style.

Using Stream and distinct()

First, convert an ArrayList into a stream by calling its stream() method; then use distinct() on that stream to filter out duplicate values so only unique items remain. To extract unique values from a stream, the collect() method with appropriate collectors allows for their retrieval.

For optimal use of distinct(), ensure your elements in an ArrayList have correctly overridden equals() in order to establish their uniqueness and define themselves correctly as distinct elements.

Algorithm

  • Create and populate an ArrayList with elements.

  • Convert an ArrayList into a stream using stream() method.

  • Apply the distinct() method on the Stream to eliminate duplicate values and retain only unique ones.

  • Convert a stream back into an arrayList or other suitable collection using collect() method and suitable collectors.

  • This new ArrayList will contain only those unique values from its source ArrayList.

Program

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class UniqueValuesExample {
   public static void main(String[] args) {
      List<String> fruits = new ArrayList<>();
      fruits.add("Apple");
      fruits.add("Orange");
      fruits.add("Banana");
      fruits.add("Orange");
      fruits.add("Mango");
      fruits.add("Apple");

      List<String> uniqueFruits = fruits.stream()
         .distinct()
         .collect(Collectors.toList());

      System.out.println("Unique fruits: " + uniqueFruits);
   }
}

Output

Unique fruits: [Apple, Orange, Banana, Mango]

Using HashSet

Launch an editor. Assemble a HashSet object as a collection that holds unique elements, then traverse each element in an ArrayList one by one to add each to HashSet, noting any duplicate values which appear. Due to HashSet not permitting duplicated values to remain, any duplicative data from ArrayLists will automatically be eliminated by HashSets.

Once iterating through an ArrayList, creating a HashSet with only unique values from that original list allows you to access only these specific ones directly or convert back into an ArrayList for further access.

This approach takes advantage of HashSets' inherent uniqueness constraint to quickly retrieve unique values from an ArrayList, offering a convenient solution in Java 8.

Algorithm

  • Create and populate an ArrayList with elements.

  • Create a HashSet object.

  • Iterate through each element in an ArrayList.

  • Add each element to the HashSet using add() method.

    • HashSet will automatically eliminate duplicate values as it only stores unique ones.

  • Once traversing an ArrayList, HashSet will contain only those unique values from that original list.

  • If desired, switch back the HashSet back into an ArrayList or use it directly as an access tool for finding unique values in it.

Program

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UniqueValuesExample {
   public static void main(String[] args) {
      List<String> animals = new ArrayList<>();
      animals.add("Lion");
      animals.add("Elephant");
      animals.add("Tiger");
      animals.add("Elephant");
      animals.add("Giraffe");
      animals.add("Lion");

      Set<String> uniqueAnimals = new HashSet<>(animals);

      System.out.println("Unique animals: " + uniqueAnimals);
   }
}

Output

Unique animals: [Elephant, Lion, Tiger, Giraffe]

Conclusion

In this tutorial, we discovered how Java 8 offers efficient and elegant solutions for extracting unique values from an ArrayList. By taking advantage of its Stream API's distinct() method and eliminating duplicate items quickly from an ArrayList to obtain new unique ones - as well as its functional programming features which enable concise yet readable code - developers are easily able to achieve this task swiftly and efficiently.

HashSet can also provide another effective means of finding unique values, by initializing it with the ArrayList; any duplicate elements will automatically be eliminated, leaving only unique entries within it.

Java 8's flexibility and convenience in handling the task of extracting unique values from an ArrayList are clear from these approaches; both methods leverage its Stream API or HashSet implementation for maximum productivity to help developers easily meet their objectives.

Updated on: 25-Jul-2023

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements