search
HomeJavajavaTutorialJava array deduplication: Getting started and mastering five common methods

Java array deduplication: Getting started and mastering five common methods

From entry to proficiency: Five common ways to remove duplication from Java arrays

Introduction: In Java development, array operations are one of the most common operations. Array deduplication is one of the problems often encountered. In this article, we will introduce five common ways to implement Java array deduplication to help you go from getting started to becoming proficient in array deduplication.

1. Use Set collection
The common way is to use the characteristics of Set collection to achieve array deduplication. Set collection is a collection that does not allow duplicate elements, so putting the elements of the array into the Set collection will automatically remove duplicate elements.

Code example:

import java.util.*;

public class ArrayDuplicateRemover {
    public static void main(String[] args) {
        // 原始数组
        Integer[] array = {1, 2, 3, 4, 3, 2, 1};
        
        // 利用Set集合去重
        Set<Integer> set = new HashSet<>(Arrays.asList(array));
        
        // 去重后的数组
        Integer[] result = set.toArray(new Integer[0]);
        
        // 打印结果
        System.out.println(Arrays.toString(result));
    }
}

2. Use loop traversal
Another common way is to use a loop to traverse the array, determine whether the elements are repeated one by one, and put the non-repeating elements into in the new array.

Code example:

import java.util.Arrays;

public class ArrayDuplicateRemover {
    public static void main(String[] args) {
        // 原始数组
        Integer[] array = {1, 2, 3, 4, 3, 2, 1};
        
        // 借助循环遍历去重
        Integer[] result = new Integer[array.length];
        int index = 0;
        for (Integer num : array) {
            boolean isDuplicate = false;
            for (int i = 0; i < index; i++) {
                if (num == result[i]) {
                    isDuplicate = true;
                    break;
                }
            }
            if (!isDuplicate) {
                result[index++] = num;
            }
        }
        
        // 去重后的数组
        result = Arrays.copyOf(result, index);
        
        // 打印结果
        System.out.println(Arrays.toString(result));
    }
}

3. Using Stream flow
After Java 8, the concept of streaming operations was introduced, which can easily handle collections and arrays. Duplicate elements can be removed using the distinct() method of the Stream stream.

Code example:

import java.util.Arrays;

public class ArrayDuplicateRemover {
    public static void main(String[] args) {
        // 原始数组
        Integer[] array = {1, 2, 3, 4, 3, 2, 1};
        
        // 利用Stream流去重
        Integer[] result = Arrays.stream(array).distinct().toArray(Integer[]::new);
        
        // 打印结果
        System.out.println(Arrays.toString(result));
    }
}

4. Using HashMap
Using HashMap to achieve array deduplication is also a common way. Traverse the array, put the array elements as Key into the HashMap, duplicate elements will be overwritten, and finally remove the Key from the HashMap.

Code example:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ArrayDuplicateRemover {
    public static void main(String[] args) {
        // 原始数组
        Integer[] array = {1, 2, 3, 4, 3, 2, 1};
        
        // 利用HashMap去重
        Map<Integer, Integer> map = new HashMap<>();
        for (Integer num : array) {
            map.put(num, num);
        }
        Integer[] result = map.keySet().toArray(new Integer[0]);
        
        // 打印结果
        System.out.println(Arrays.toString(result));
    }
}

5. Using recursion
Recursion is an advanced programming technique that can be used to achieve array deduplication. Each recursion compares the first element of the array with the following elements. If they are the same, the following elements are removed until the recursion ends.

Code example:

import java.util.Arrays;

public class ArrayDuplicateRemover {
    public static void main(String[] args) {
        // 原始数组
        Integer[] array = {1, 2, 3, 4, 3, 2, 1};
        
        // 利用递归去重
        Integer[] result = removeDuplicates(array, array.length);
        
        // 打印结果
        System.out.println(Arrays.toString(result));
    }
    
    public static Integer[] removeDuplicates(Integer[] array, int length) {
        if (length == 1) {
            return array;
        }
        
        if (array[0] == array[length-1]) {
            return removeDuplicates(Arrays.copyOf(array, length-1), length-1);
        } else {
            return removeDuplicates(array, length-1);
        }
    }
}

Conclusion: Through the above five common methods, we can easily implement Java array deduplication operations. Whether we use Set collection, loop traversal, Stream flow, HashMap or recursion, it can help us better handle the needs of array deduplication. I hope this article can help you from getting started to becoming proficient in Java array deduplication.

The above is the detailed content of Java array deduplication: Getting started and mastering five common methods. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor