Home Java javaTutorial Java array deduplication: Getting started and mastering five common methods

Java array deduplication: Getting started and mastering five common methods

Dec 23, 2023 pm 03:04 PM
java array deduplication

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));
    }
}
Copy after login

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));
    }
}
Copy after login

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));
    }
}
Copy after login

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));
    }
}
Copy after login

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);
        }
    }
}
Copy after login

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 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

Video Face Swap

Video Face Swap

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

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 to restrict access to specific interfaces of nested H5 pages through OAuth2.0's scope mechanism? How to restrict access to specific interfaces of nested H5 pages through OAuth2.0's scope mechanism? Apr 19, 2025 pm 02:30 PM

How to use OAuth2.0's access_token to achieve control of interface access permissions? In the application of OAuth2.0, how to ensure that the...

In back-end development, how to distinguish the responsibilities of the service layer and the dao layer? In back-end development, how to distinguish the responsibilities of the service layer and the dao layer? Apr 19, 2025 pm 01:51 PM

Discussing the hierarchical architecture in back-end development. In back-end development, hierarchical architecture is a common design pattern, usually including controller, service and dao three layers...

In Java remote debugging, how to correctly obtain constant values ​​on remote servers? In Java remote debugging, how to correctly obtain constant values ​​on remote servers? Apr 19, 2025 pm 01:54 PM

Questions and Answers about constant acquisition in Java Remote Debugging When using Java for remote debugging, many developers may encounter some difficult phenomena. It...

How to choose Java project management tools when learning back-end development? How to choose Java project management tools when learning back-end development? Apr 19, 2025 pm 02:15 PM

Confused with choosing Java project management tools for beginners. For those who are just beginning to learn backend development, choosing the right project management tools is crucial...

Ultimate consistency in distributed systems: how to apply and how to compensate for data inconsistencies? Ultimate consistency in distributed systems: how to apply and how to compensate for data inconsistencies? Apr 19, 2025 pm 02:24 PM

Exploring the application of ultimate consistency in distributed systems Distributed transaction processing has always been a problem in distributed system architecture. To solve the problem...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

Why does the Python script not be found when submitting a PyFlink job on YARN? Why does the Python script not be found when submitting a PyFlink job on YARN? Apr 19, 2025 pm 02:06 PM

Analysis of the reason why Python script cannot be found when submitting a PyFlink job on YARN When you try to submit a PyFlink job through YARN, you may encounter...

How to dynamically modify the savePath parameter of @Excel annotation in easypoi when project starts in Java? How to dynamically modify the savePath parameter of @Excel annotation in easypoi when project starts in Java? Apr 19, 2025 pm 02:09 PM

How to dynamically configure the parameters of entity class annotations in Java During the development process, we often encounter the need to dynamically configure the annotation parameters according to different environments...

See all articles