数组、对象去重

在做批量查询时,会对传入的参数进行去重,第一想到的就是利用set集合,因为set集合存值是唯一的,没有重复的。利用set集合无序,唯一的特点可以对数组,对象进行去重操作。

 	/**
     * 数组去重
     * @param array 数组参数
     * @return
     */
    public static String[] removeRepeat(String[] array) {
        Set<String> set = new HashSet<>();
        for (int i = 0; i < array.length; i++) {
            set.add(array[i].trim());
        }
        String[] arr = set.toArray(new String[set.size()]);
        return arr;
    }

 public static String[] removeRepeat(String[] array) {
        LinkedHashSet<String> set = new LinkedHashSet<>(); //存放顺序和取出顺序一致
        for (int i = 0; i < array.length; i++) {
            if(!array[i].trim().equals("")){
                set.add(array[i].trim());
            }else{
                continue;
            }

        }
        String[] arr = set.toArray(new String[set.size()]);
        return arr;
    }


//集合对象去重
List<String> list = new ArrayList<>();
		list.add("aa");
		list.add("aa");
		list.add("bb");
		list.add("cc");
		list.add("cc");
		Set<String> set2= new HashSet<>();
		set2.addAll(list);

参考博文:https://blog.csdn.net/zh137289/article/details/85050475

原文地址:https://www.cnblogs.com/jasonboren/p/12489444.html