编程语言
首页 > 编程语言> > 廖雪峰Java5集合-4Set-1使用Set

廖雪峰Java5集合-4Set-1使用Set

作者:互联网

集合

Set用于存储不重复的元素集合:

public class Main {
    public static void main(String[] args) throws IOException {
        Set<String> aset = new HashSet<>();
        System.out.println("1"+aset.add("tom"));
        System.out.println("2"+aset.add("tom"));//重复添加失败,set不能存储重复元素
        System.out.println("3"+aset.add("jerry"));

        System.out.println("集合长度"+aset.size());

        System.out.println("4"+aset.remove("jerry"));
        System.out.println("5"+aset.remove("kitty"));
        System.out.println("6"+aset.contains("tom"));
        System.out.println("7"+aset.contains("jerry"));
    }
}

Set不保证有序:

public class Main {
    public static void main(String[] args) throws IOException {
        //HashSet不能保证有序
        Set<String> aset = new HashSet<>();
        aset.add("apple");
        aset.add("pear");
        aset.add("orange");
        for(Object o:aset){
            System.out.println(o.toString());
        }
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        Set<String> aset = new TreeSet<>();
        //TreeSet按元素顺序排序
        aset.add("apple");
        aset.add("pear");
        aset.add("orange");
        for(Object o:aset){
            System.out.println(o.toString());
        }
    }
}


TreeSet可以自定义排序算法

示例:利用set去除List中的重复元素

public class Main {
    public static void main(String[] args) throws IOException {
        List<String> list1 = Arrays.asList("pear","apple","banana","orange","apple","banana");
        System.out.println(removeDuplicate(list1));
    }
    static List<String> removeDuplicate(List<String> list){
        Set<String> set = new HashSet<>(list);
        return new ArrayList<>(set);
    }
}


替换为TreeSet,对元素进行排序

public class Main {
    public static void main(String[] args) throws IOException {
        List<String> list1 = Arrays.asList("pear","apple","banana","orange","apple","banana");
        System.out.println(removeDuplicate(list1));
    }
    static List<String> removeDuplicate(List<String> list){
        Set<String> set = new TreeSet<>(list);
        return new ArrayList<>(set);
    }
}


自定义排序算法

public class Main {
    public static void main(String[] args) throws IOException {
        List<String> list1 = Arrays.asList("pear","apple","banana","orange","apple","banana");
        System.out.println(removeDuplicate(list1));
    }
    static List<String> removeDuplicate(List<String> list){
        Set<String> set = new TreeSet<>(new Comparator<String>() {
            ////自定义排序算法
            @Override
            public int compare(String o1, String o2) {
                //反序
                return -o1.compareTo(o2);
            }
        });
        set.addAll(list);
        return new ArrayList<>(set);
    }
}

总结

标签:Set,4Set,System,aset,Java5,println,public,out
来源: https://www.cnblogs.com/csj2018/p/10548183.html