Home Java javaTutorial An in-depth analysis of five practical methods for deduplicating Java arrays

An in-depth analysis of five practical methods for deduplicating Java arrays

Dec 23, 2023 am 09:21 AM
java array Remove duplicates Practical methods

An in-depth analysis of five practical methods for deduplicating Java arrays

In-depth analysis of five practical methods for Java array deduplication

In Java, processing arrays is a very common operation. Array deduplication is a problem often encountered in actual development. This article will provide an in-depth analysis of five practical methods for Java array deduplication and provide specific code examples.

1. Use HashSet to remove duplicates
HashSet is a collection in Java that has the function of automatic deduplication. We can use the characteristics of HashSet to add elements in the array to HashSet to achieve the effect of deduplication.

import java.util.HashSet;
import java.util.Arrays;

public class ArrayDuplicateRemoval {
    public static int[] removeDuplicates(int[] array){
        HashSet<Integer> set = new HashSet<>();
        for(int i=0;i<array.length;i++){
            set.add(array[i]);
        }
        int[] result = new int[set.size()];
        int index=0;
        for(Integer num:set){
            result[index++] = num;
        }
        return result;
    }
    public static void main(String[] args){
        int[] array = {1, 2, 3, 4, 4, 5, 5, 6};
        int[] result = removeDuplicates(array);
        System.out.println(Arrays.toString(result));
    }
}
Copy after login

2. Use LinkedHashSet to remove duplication
LinkedHashSet is a subclass of HashSet. In addition to having the deduplication function, it can also maintain the insertion order. If you need to maintain the original order and remove duplicate elements, you can use LinkedHashSet.

import java.util.LinkedHashSet;
import java.util.Arrays;

public class ArrayDuplicateRemoval {
    public static int[] removeDuplicates(int[] array){
        LinkedHashSet<Integer> set = new LinkedHashSet<>();
        for(int i=0;i<array.length;i++){
            set.add(array[i]);
        }
        int[] result = new int[set.size()];
        int index=0;
        for(Integer num:set){
            result[index++] = num;
        }
        return result;
    }
    public static void main(String[] args){
        int[] array = {1, 2, 3, 4, 4, 5, 5, 6};
        int[] result = removeDuplicates(array);
        System.out.println(Arrays.toString(result));
    }
}
Copy after login

3. Use TreeSet to remove duplicates
TreeSet is an ordered set, which naturally sorts the elements by default. Using the deduplication feature of TreeSet, you can add elements in the array to the TreeSet, and then convert the TreeSet into an array to achieve deduplication.

import java.util.TreeSet;
import java.util.Arrays;

public class ArrayDuplicateRemoval {
    public static int[] removeDuplicates(int[] array){
        TreeSet<Integer> set = new TreeSet<>();
        for(int i=0;i<array.length;i++){
            set.add(array[i]);
        }
        int[] result = new int[set.size()];
        int index=0;
        for(Integer num:set){
            result[index++] = num;
        }
        return result;
    }
    public static void main(String[] args){
        int[] array = {1, 2, 3, 4, 4, 5, 5, 6};
        int[] result = removeDuplicates(array);
        System.out.println(Arrays.toString(result));
    }
}
Copy after login

4. Use Stream API to remove duplicates
Stream API is a new API introduced in Java 8, which provides a streaming operation method. Combined with the distinct method of Stream, you can easily remove duplicate arrays.

import java.util.Arrays;
import java.util.stream.IntStream;

public class ArrayDuplicateRemoval {
    public static int[] removeDuplicates(int[] array){
        int[] result = IntStream.of(array).distinct().toArray();
        return result;
    }
    public static void main(String[] args){
        int[] array = {1, 2, 3, 4, 4, 5, 5, 6};
        int[] result = removeDuplicates(array);
        System.out.println(Arrays.toString(result));
    }
}
Copy after login

5. Use double loop to remove duplicates
The last method is to use double loop to traverse the array to mark and remove duplicate elements.

import java.util.Arrays;

public class ArrayDuplicateRemoval {
    public static int[] removeDuplicates(int[] array){
        int length = array.length;
        for(int i=0;i<length-1;i++){
            if(array[i]!=-1){
                for(int j=i+1;j<length;j++){
                    if(array[j]==array[i]){
                        array[j] = -1; // 标记为重复元素
                    }
                }
            }
        }
        int[] result = new int[length];
        int index = 0;
        for(int i=0;i<length;i++){
            if(array[i]!=-1){
                result[index++] = array[i];
            }
        }
        return Arrays.copyOf(result, index);
    }
    public static void main(String[] args){
        int[] array = {1, 2, 3, 4, 4, 5, 5, 6};
        int[] result = removeDuplicates(array);
        System.out.println(Arrays.toString(result));
    }
}
Copy after login

Through the above introduction, we have explained in detail five practical methods of Java array deduplication and provided specific code examples. Depending on the actual situation and needs, you can choose a suitable method to solve the problem of array deduplication. I hope this article will be helpful to you in actual development!

The above is the detailed content of An in-depth analysis of five practical methods for deduplicating Java arrays. 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)

Revealing Five Efficient Java Array Deduplication Methods Revealing Five Efficient Java Array Deduplication Methods Dec 23, 2023 pm 02:46 PM

Five efficient Java array deduplication methods revealed In the Java development process, we often encounter situations where we need to deduplicate arrays. Deduplication is to remove duplicate elements in an array and keep only one. This article will introduce five efficient Java array deduplication methods and provide specific code examples. Method 1: Use HashSet to deduplicate HashSet is an unordered, non-duplicate collection that automatically deduplicates when adding elements. Therefore, we can use the characteristics of HashSet to deduplicate arrays. public

Revealing the efficient data deduplication method in Pandas: Tips for quickly removing duplicate data Revealing the efficient data deduplication method in Pandas: Tips for quickly removing duplicate data Jan 24, 2024 am 08:12 AM

The secret of Pandas deduplication method: a fast and efficient way to deduplicate data, which requires specific code examples. In the process of data analysis and processing, duplication in the data is often encountered. Duplicate data may mislead the analysis results, so deduplication is a very important step. Pandas, a powerful data processing library, provides a variety of methods to achieve data deduplication. This article will introduce some commonly used deduplication methods, and attach specific code examples. The most common case of deduplication based on a single column is based on whether the value of a certain column is duplicated.

Common ways to add elements to Java arrays Common ways to add elements to Java arrays Feb 21, 2024 am 11:21 AM

Common ways to add elements to Java arrays, specific code examples are required In Java, an array is a common data structure that can store multiple elements of the same type. In actual development, we often need to add new elements to the array. This article will introduce common methods of adding elements to arrays in Java and provide specific code examples. A simple way to create a new array using a loop is to create a new array, copy the elements of the old array into the new array, and add the new elements. The code example is as follows: //original array i

How to optimize collection sorting and deduplication performance in Java development How to optimize collection sorting and deduplication performance in Java development Jul 02, 2023 am 11:25 AM

In Java development, collection sorting and deduplication are common requirements. However, performance often becomes an issue when dealing with large data collections. This article will introduce some optimization techniques to help improve the performance of collection sorting and deduplication. 1. Use appropriate data structures. In Java, the most commonly used data structures are ArrayList and HashSet. ArrayList is suitable for situations where the order of elements needs to be maintained, while HashSet is suitable for situations where duplication needs to be eliminated. In sorting and deduplication scenarios, we can use

How to remove duplicates in word How to remove duplicates in word Mar 20, 2024 pm 02:13 PM

Sometimes when we use word office software to operate and edit files, some content is repeated. How can we quickly find the repeatedly entered information and then delete the repeated content? It is easy to find duplicates in an Excel spreadsheet, but will you find duplicates in a word document? Below, we will share how to remove duplicates in word, so that you can quickly find duplicate content and perform editing operations. First, open a new Word document and enter some content in the document. Consider inserting some repetitive parts to help demonstrate operations. 2. To find duplicate content, we need to click [Start]-[Search] tool in the menu bar, select [Advanced Search] in the drop-down menu, and click

What are the methods to remove duplicates in pandas? What are the methods to remove duplicates in pandas? Nov 22, 2023 am 11:55 AM

The pandas deduplication methods are: 1. Use the drop_duplicates() method; 2. Use the duplicated() method; 3. Use the unique() method; 4. Use the value_counts() method. Detailed introduction: 1. Use the drop_duplicates() method to delete duplicate rows in the data frame and return a new data frame. It can set parameters to control how to perform deduplication, such as specifying the retention order and deduplication after deduplication. Time comparison columns and so on.

How to perform deduplication operation after the PHP array is shuffled? How to perform deduplication operation after the PHP array is shuffled? May 02, 2024 pm 01:33 PM

In PHP, you can use the following steps to disrupt the order of the array and then perform deduplication operations: Use the shuffle() function to disrupt the order of the array. Use the array_unique() function to deduplicate the array and remove duplicate elements.

How to achieve deduplication of data in PHP arrays? How to achieve deduplication of data in PHP arrays? Apr 26, 2024 pm 06:51 PM

Three methods to deduplicate PHP arrays: use the array_unique() function to remove duplicate values ​​based on element values ​​and retain the key value order. Use the array_filter() function to remove duplicate elements based on the conditions of the callback function. Use the SplObjectStorage class to take advantage of the uniqueness of objects to achieve array deduplication and retain key-value associations.

See all articles