java List集合常用工具类

比较一个list集合里是否有重复

/** 
 * 比较一个list集合里是否有重复
 * */
public static <T> boolean isRepeat(List<T> list) {  
    Set<T> set = new HashSet<>(list);
    return set.size() != list.size();
}

比较List<对象>是否有重复

private Boolean isRepeat(List<Role> roleList) {
        Set<Role> roles = new TreeSet<>(Comparator.comparing(Role::getCode));  
        // Set<Role> roles = new TreeSet<>(Comparator.comparing(item -> item.getCode().toString() + item.getCodeType()));
        roles.addAll(roleList);
        if (set.size() < roleList.size()) {
            return true;
        }
        return false;
    }

比较两个集合是否有重复

/** 
 * 比较两个集合是否有重复
 * */  
public static boolean isRepeat(List<Object> list1, List<Object> list2){  
    Set<Object> set1 = new HashSet<>(list1);
    Set<Object> set2 = new HashSet<>(list2);
    Set<Object> setAll = new HashSet<>(set1);
    setAll.addAll(set2);
    int setSize = set1.size() + set2.size();
    return setAll.size() != setSize;
}  

单个List集合去除重复

/**
 * 单个List集合去除重复
 * */
public static List<Object> removeRepeat(List<Object> list) {  
    Set<Object> set = new HashSet<>(list);
    return new ArrayList<>(set);
}  

单个List集合去除重复 (根据对象中的属性进行去除重复)
demo1

List<Role> roleList = listRole();
private Comparator<Role> roleComparator = new Comparator<Role>() {  
    public int compare(Role r1, Role r2) {  
        return r1.getCode().compareTo(r2.getCode());  
    }  
};  

Set<Role> roles = new TreeSet<>(this.roleComparator);  
roles.addAll(roleList);  

//java8 简化版
Set<Role> roles = new TreeSet<>(Comparator.comparing(Role::getCode));  
roles.addAll(roleList);

demo2 对象去重之后转化另一个对象集合

List<WhiteListIndustry> list = new ArrayList<>();
WhiteListIndustry item = new WhiteListIndustry();
item.setIndustryName("test1");
item.setIndustryCode(2000001);
WhiteListIndustry item2 = new WhiteListIndustry();
item2.setIndustryName("test1");
item2.setIndustryCode(2000001);

list.add(item);
list.add(item2);

Set<WhiteListIndustry> treeSet = new TreeSet<>(Comparator.comparing(WhiteListIndustry::getIndustryCode));
treeSet.addAll(list);

List<KeyValueVO> kvList = treeSet.stream().map(i ->
        new KeyValueVO(i.getIndustryName(), i.getIndustryCode())
).collect(Collectors.toList());

比较两个集合是否有重复(有相同移除第一个集合中的相同值)

/** 
 * 比较两个集合是否有重复(有相同移除第一个集合中的相同值) 
 * */  
//一般法  
public static List<Object> removeRepeat(List<Object> list1, List<Object> list2) {  
    List<Object> newList = new ArrayList<Object>();  
    for (Object o1 : list1) {  
        boolean flag = true;  
        for (Object o2 : list2) {  
            if (o1.equals(o2)){  
                flag = false;  
                break;  
            }  
        }  
        if (flag){
            newList.add(o1);  
        }
    }  
    return newList;  
}
//方法二:
public static List<Object> removeRepeat2(List<Object> list1, List<Object> list2) {  
    list1.removeAll(list2);  
    return list1;  
} 

比较两个list集合:childList 中 包含 parentList的 map 中的 key值,如果相等重新放到一个map<String,List<Map<String,String>>里

/** 
* 比较两个list集合中map:childList 中 包含 parentList的 map 中的 key值,如果相等重新放到一个map<String,List<Map<String,String>>里   
*  
* */  
public static Map<String, List<Map<String, String>>> getMapsByKeyId(List<Map<String, String>> parentList,  
        List<Map<String, String>> childList, String keyId) {  
    Map<String, List<Map<String, String>>> newMap = new HashMap<>();
    for (Map<String, String> parent : parentList) {
        String value = parent.get(keyId);
        List<Map<String, String>> newList = new ArrayList<>();
        for (Map<String, String> child : childList) {
            if (child.get(keyId).equals(value))
                newList.add(child);
        }
        newMap.put(value, newList);
    }
    return newMap;
}  
//调用方式:
Map<String, List<Map<String,String>>> mapNew2 = getMapsByKeyId(list1,list2,"aid");

Map<String, List<Map<String,String>>> mapNew3 = getMapsByKeyId(list2,list3,"bid");

求两个集合的交集

/** 
* 求两个集合的交集(即两个集合都共有的) 
* */  
//最优法   利用hash这种很有用的数据结构来实现。我们知道,hash的特点之一就是不允许有重复元素,即hash表中的元素都是唯一的。所以,我们的思路就是:先把第一个集合的所有元素都放进hashSet中,时间复杂度O(M);再把第二个集合中的元素放进hashSet中,如果有重复元素,就是这2个集合的交集,时间复杂度为O(N)。即总的时间复杂度从O(M*N)降低到了O(M+N)。  
public static List<String> getIntersection(List<String> list1, List<String> list2) {  
    List<String> commonList = new ArrayList<>();
    Set<Object> hashSet = new HashSet<>();
    Collections.addAll(hashSet,list1);

    for (String item : list2) {
        if (!hashSet.add(item)) {
            commonList.add(item);
        }
    }
    return commonList;
}  

求两个集合的并集(即两个集合中重复的只保留一个)

/** 
 * 求两个集合的并集(即两个集合中重复的只保留一个) 
 * */  
public static List<Object> unionAll(List<Object> list1, List<Object> list2) {  
    list1.removeAll(list2);  
    list1.addAll(list2);  
    return list1;  
}  

计算集合中元素重复次数

    List list = new ArrayList();
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("d");
    list.add("b");
    list.add("c");
    list.add("a");
    list.add("a");
    list.add("a");

    System.out.println("\n例子1 - 计算'a'出现的次数");
    System.out.println("a : " + Collections.frequency(list, "a"));

    System.out.println("\n例子2 - 计算所有对象出现的次数");
    Set uniqueSet = new HashSet(list);
    for (String temp : uniqueSet) {
        System.out.println(temp + ": " + Collections.frequency(list, temp));
    }

    System.out.println("\n例子3 -用Map来计算对象出现的次数");
    Map map = new HashMap();

    for (String temp : list) {
        Integer count = map.get(temp);
        map.put(temp, (count == null) ? 1 : count + 1);
    }
    printMap(map);

    System.out.println("\nMap排序-以key排序");
    Map treeMap = new TreeMap(map);
    printMap(treeMap);
 
    public static void printMap(Map map) {
        for (Map.Entry entry : map.entrySet()) {
            System.out.println("Key-value : " + entry.getKey() + "- "
                    + entry.getValue());
        }
    }

set的交集, 并集, 差集 使用google guava

HashSet setA = newHashSet(1, 2, 3, 4, 5);  
HashSet setB = newHashSet(4, 5, 6, 7, 8);  

SetView union = Sets.union(setA, setB);    
System.out.println("union:");  
for (Integer integer : union)  {
    System.out.println(integer);           //union 并集:12345867
}

SetView difference = Sets.difference(setA, setB);  
System.out.println("difference:");  
for (Integer integer : difference)  {
    System.out.println(integer);        //difference 差集:123
}

SetView intersection = Sets.intersection(setA, setB);  
System.out.println("intersection:");  
for (Integer integer : intersection) {
    System.out.println(integer);  //intersection 交集:45
}

map的交集,并集,差集 使用google guava

HashMap<String, Integer> mapA = Maps.newHashMap();
mapA.put("a", 1);mapA.put("b", 2);mapA.put("c", 3);

HashMap<String, Integer> mapB = Maps.newHashMap();
mapB.put("b", 20);mapB.put("c", 3);mapB.put("d", 4);

MapDifference differenceMap = Maps.difference(mapA, mapB);
differenceMap.areEqual();
Map entriesDiffering = differenceMap.entriesDiffering();
Map entriesOnlyLeft = differenceMap.entriesOnlyOnLeft();
Map entriesOnlyRight = differenceMap.entriesOnlyOnRight();
Map entriesInCommon = differenceMap.entriesInCommon();

System.out.println(entriesDiffering);   // {b=(2, 20)}
System.out.println(entriesOnlyLeft);    // {a=1}
System.out.println(entriesOnlyRight);   // {d=4}
System.out.println(entriesInCommon);    // {c=3}

版权声明:本文为fzy629442466原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。