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

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

高洛峰
高洛峰Original
2017-03-20 17:10:211945browse

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));
    }

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);
    }


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!

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