Java数组/集合去重

一、对数组进行去重:

     1、HashSet去重

import java.util.*;

/**
 * @author: Lucifer
 * @create: 2018-11-20 10:42
 * @description:
 **/
public class test1 {

    public static void main(String[] args) {
        int[] a={1,2,2,3,3,5,4,4,8,6,18};
        Set set=new HashSet();
        for (int i = 0; i < a.length; i++) {
            set.add(a[i]);
        }
        if (set.iterator().hasNext()){
            System.out.println(set.toString());
        }
    }

}

注:输出结果无序:

[1, 2, 18, 3, 4, 5, 6, 8]

用TreeSet可以实现既排序又去重,Set set=new TreeSet();

[1, 2, 3, 4, 5, 6, 8, 18]

   2、利用集合

import java.util.*;

/**
 * @author: Lucifer
 * @create: 2018-11-20 10:42
 * @description:
 **/
public class test1 {

    public static void main(String[] args) {
        int[] a={1,2,2,3,3,5,4,4,8,6,18};
        List list=new ArrayList();
        List tmplist=new ArrayList();
        for (int i = 0; i < a.length; i++) {
                list.add(i,a[i]);
        }
        Iterator iter = list.iterator();
        while (iter.hasNext()){
            Object t=iter.next();
            if(tmplist.contains(t)){
                System.out.println(list.toString());
                iter.remove();
            }else{
                tmplist.add(t);
            }
        }
        System.out.println("tmplist"+tmplist.toString());
    }

}

 注:输出结果:

[1, 2, 2, 3, 3, 5, 4, 4, 8, 6, 18]
[1, 2, 3, 3, 5, 4, 4, 8, 6, 18]
[1, 2, 3, 5, 4, 4, 8, 6, 18]
tmplist[1, 2, 3, 5, 4, 8, 6, 18]

二、对集合进行去重

    1、利用hashset去重

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {

    public static void main(String[] args) {
        List list=new ArrayList<>();
        list.add("a");
        list.add("ab");
        list.add("ca");
        list.add("e");
        list.add("b");
        list.add("ab");
        System.out.println(list);
        Set hashSet = new HashSet<>(list);
        System.out.println(hashSet);
    }
}

ps:
       Set hashSet = new HashSet<>(list); 等同于Set hashSet = new HashSet<>();set.addAll(list);

你可能感兴趣的:(面试/笔试)