Home > Java > javaTutorial > body text

Detailed explanation of how to remove duplicate values ​​from an array in Java

高洛峰
Release: 2017-03-20 17:10:21
Original
1901 people have browsed it

You can use the set method, because the set method itself does not allow duplicate values ​​

The code is as follows:

public static void main(String[] args) {
        int[] a={1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3};
        System.out.println(Arrays.toString(a));
        Set<Integer> set=new HashSet<Integer>();
        for (Integer integer : a) {
            set.add(integer);
        }
        Integer[] b=set.toArray(new Integer[0]);
        System.out.println(Arrays.toString(b));
    }
Copy after login

Of course, you can also use this method to remove duplicate numbers in the list

public static void main(String[] args) {
        List<Integer> list=Arrays.asList(1,2,3,1,2,3,4,5,6,4,5,6);
        Set set=new HashSet<Integer>(list);
        list=new ArrayList<Integer>(set);
        System.out.println(list);
    }
Copy after login


The above is the detailed content of Detailed explanation of how to remove duplicate values ​​from an array in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!