java实现俩个list的交集,我目前已知俩种

1  hashMap

public class GetTwoListCommon2 {
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        for (int i = 1; i <= 1000000; i++) {
            list1.add(i);
            list2.add(1000000 - i);
        }
        long startTime = System.currentTimeMillis();
        //最后结果集
        List<Integer> resultList = new ArrayList<>();
        //中间存储
        Map<String, Integer> map = new HashMap<>();
        list2.forEach(i2 -> {
            map.put(i2 + "", i2);
        });
        list1.forEach(i1 -> {
            Integer m = map.get(i1 + "");
            if (m != null) {
                resultList.add(i1);
            }
        });
        System.out.println("耗时:" + (System.currentTimeMillis() - startTime) + "ms");
    }
}

耗时:

java双层list扁平化 java两个list_i++

2 HashSet

public class GetTwoListCommon {
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        for (int i = 1; i <= 1000000; i++) {
            list1.add(i);
            list2.add(1000000 - i);
        }
        //记录开始时间
        long startTime = System.currentTimeMillis();
        //最后结果集
        List<Integer> resultList = new ArrayList<>();
        //中间存储
        Map<String, Integer> map = new HashMap<>();
        HashSet<Integer> hashSet = new HashSet<>();
        list2.forEach(i2 -> {
            hashSet.add(i2);
        });
        list1.forEach(i1->{
            if (hashSet.contains(i1)){
                resultList.add(i1);
            }
        });
        System.out.println("耗时:" + (System.currentTimeMillis() - startTime) + "ms");
    }
}

java双层list扁平化 java两个list_System_02

 

结果显而易见!!!  over