Table of Contents
Array list
method
algorithm
program
Output
in conclusion
Home Java javaTutorial How to get unique values ​​from ArrayList using Java 8?

How to get unique values ​​from ArrayList using Java 8?

Sep 05, 2023 am 11:01 AM

如何使用Java 8从ArrayList中获取唯一值?

Extracting unique values ​​from an ArrayList becomes easier and faster by leveraging Java 8’s functional programming features like the Stream API, streams, and lambda expressions. Using these features, you can extract different elements without tedious iteration or manual inspection; lambda expressions make this task easier by allowing you to write concise and readable code. Whether dealing with large data sets or simply eliminating duplicates, Java 8 provides powerful and elegant solutions to retrieve unique values ​​from ArrayList

Array list

Java's ArrayList class implements the List interface, providing functions similar to dynamic arrays for storing and operating collections of elements in adjustable arrays. When elements are added to or removed from an ArrayList array, its size is automatically adjusted, providing flexibility and convenience.

There are many methods to access, modify, add and delete elements in ArrayList. Elements can be accessed using the get() method and modified using the set() method; in addition, elements can be added at a specific position in the list using the add() method, and elements can be removed at a specific position using the remove() method, or at the end of the list. Add or remove elements

ArrayList<String> names = new ArrayList<>();
Copy after login

method

Java 8 provides several ways to find unique values ​​in an arrayList. Below are two strategies that are often used.

  • Use Stream and distinct()

  • Use hash set

Both methods provide an efficient way to extract unique values ​​from an ArrayList using Java 8 features, so just choose the method that best suits your requirements and coding style.

Use Stream and distinct()

First, convert the ArrayList to a stream by calling its stream() method; then use unique() on the stream to filter out duplicate values ​​so that only unique items are retained. In order to extract unique values ​​from the stream, the collect() method with an appropriate collector allows retrieving them.

For optimal use of distinct(), please ensure that the elements in the ArrayList have correctly overridden the equals() method to ensure their uniqueness, and correctly define themselves as distinct elements

algorithm

  • Create an ArrayList and fill it with elements.

  • Use the stream() method to convert ArrayList to a stream

  • Apply the unique() method on a Stream to eliminate duplicate values ​​and keep only unique values.

  • Convert the stream back to an ArrayList or other appropriate collection using the collect() method and an appropriate collector

  • This new ArrayList will only contain 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);
   }
}
Copy after login

Output

Unique fruits: [Apple, Orange, Banana, Mango]
Copy after login

Use HashSet

Start the editor. Assemble the HashSet objects into a collection that holds unique elements, then iterate through each element in the ArrayList one by one to add it to the HashSet, noting any duplicate values ​​that occur. Since HashSet does not allow duplicate values ​​to exist, any duplicate data in the ArrayList will be automatically eliminated by HashSet

After iterating the ArrayList, creating a HashSet containing only the unique values ​​from the original list allows you to access those specific values ​​directly or convert back to an ArrayList for further access.

This method takes advantage of the inherent uniqueness constraint of HashSet to quickly retrieve unique values ​​from the ArrayList, providing a convenient solution in Java 8.

algorithm

  • Create an ArrayList and fill it with elements.

  • Create a HashSet object.

  • Traverse each element in ArrayList

  • Use the add() method to add each element to the HashSet

    • HashSet will automatically eliminate duplicate values ​​because it only stores unique values.

  • After traversing the ArrayList, the HashSet will contain only those unique values ​​in the original list.

  • You can switch the HashSet back to an ArrayList if needed, or use it directly as an access tool to find unique values ​​within 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);
   }
}
Copy after login

Output

Unique animals: [Elephant, Lion, Tiger, Giraffe]
Copy after login

in conclusion

In this tutorial, we saw how Java 8 provides an efficient and elegant solution to extract unique values ​​from an ArrayList. By leveraging its Stream API's unique() method and quickly eliminating duplicates from an ArrayList to get new unique items, and its functional programming capabilities for concise and readable code, developers can do it easily, quickly, and efficiently this task.

HashSet can also provide another efficient way to find unique values ​​by initializing it with an ArrayList; any duplicate elements are automatically eliminated, leaving only the unique entries within it.

Java 8’s flexibility and convenience in handling the task of extracting unique values ​​from an ArrayList is clearly evident from these methods; both of them leverage its Stream API or HashSet implementation for maximum productivity, helping developers achieve their goals easily.

The above is the detailed content of How to get unique values ​​from ArrayList using Java 8?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

See all articles