package com.kaifamiao;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>() {{
            for (int i = 0; i < 100000; i++) {
                add(13);add(3);add(34);add(79);add(118);
                add(34);add(11);add(34);
            }

        }};
//        System.out.println("原集合:" + list);
        System.out.println("原集合大小:" + list.size());

        exec(Main::qcHashSet,list);
        exec(Main::qcTreeSet,list);
        exec(Main::qcLinkedHashSet,list);
        exec(Main::qcIterator,list);
        exec(Main::qcStream,list);
        exec(Main::qcContains,list);



    }
    //exec函数的参数是函数,然后运行该函数,函数有个参数是list

    public static void exec(Consumer<List> function, List<Integer> parameter) {
        //程序运行时间
        long startTime = System.nanoTime();
        // 调用传入的函数,传入列表
        function.accept(parameter);
        long endTime = System.nanoTime();
        System.out.println("\t\t程序运行时间:" + (endTime - startTime) + " 纳秒");

    }

    public static void qcHashSet(List<Integer> list) {
        HashSet<Integer> set = new HashSet<>(list);
        System.out.print("HashSet 去重集合:" + set);
    }

    public static void qcTreeSet(List<Integer> list) {
        TreeSet<Integer> set = new TreeSet<>(list);
        System.out.print("TreeSe 去重集合:" + set);
    }
    public static void qcLinkedHashSet(List<Integer> list) {
        LinkedHashSet<Integer> set = new LinkedHashSet<>(list);
        System.out.print("LinkedHashSet 去重集合:" + set);
    }

    public static void qcIterator(List<Integer> list) {
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            // 获取循环的值
            Integer item = iterator.next();
            // 如果存在两个相同的值
            if (list.indexOf(item) != list.lastIndexOf(item)) {
                // 移除最后那个相同的值
                iterator.remove();
            }
        }
        System.out.print("Iterator 去重集合:" + list);
    }

    public static void qcStream(List<Integer> list) {
        list = list.stream().distinct().collect(Collectors.toList());
        System.out.print("Stream 去重集合:" + list);
    }

    public static void qcContains(List<Integer> list) {
        List<Integer> newList = new ArrayList<>(list.size());
        list.forEach(i -> {
            if (!newList.contains(i)) { // 如果新集合中不存在则插入
                newList.add(i);
            }
        });
        System.out.print("contains 去重集合:" + newList);
    }
}

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.