两个List集合取交集、并集、差集

业务场景:根据用户查询权限,入参:UserCodelastQueryTime(上次查询时间),出参:权限变化的列表。
oldList(上次查询到的权限列表),currList(当前查询到的权限列表),比对两个list找出:移除和增加的权限加以标识(1–增加,-1–删除)返回。

原逻辑处理方法:循环currList,如果oldList中不包含即为增加的权限列表,反之,循环oldList,如果currList中不包含即为移除的权限列表,代码如下(简略写没运行,比较笨拙):

//之前写的已经删了手动打下(add处有问题应该用map,将就着看吧)
List<String> removeList =new ArrayList<String>();
List<String> addList =new ArrayList<String>();
for(String old:currList){
    if(!currList.contains(old)){
        removeList.add(old,"-1")
    }
}
for(String curr:oldList){
    if(!oldList.contains(curr)){
        addList.add(curr,"1")
    }
}

用Java8中的 lambda表达式处理:

//AppAuths返回的变化列表
// 移除权限:上次与当前的权限取差集 (oldAppPrivileges - currAppPrivileges)
List<AppPrivilege> removePrivileges = oldAppPrivileges.stream()
.filter(oldPrivilege ->!currAppPrivileges.contains(oldPrivilege)).collect(toList());
removePrivileges.parallelStream().forEachOrdered(removePrivilege -> 
appAuths.add(new AppAuths(removePrivilege, "-1")));
 
// 增加权限:当前与上次的权限取差集 (currAppPrivileges - oldAppPrivileges)
List<AppPrivilege> addPrivileges = currAppPrivileges.stream()
.filter(currPrivilege ->!oldAppPrivileges.contains(currPrivilege)).collect(toList());
addPrivileges.parallelStream().forEachOrdered(addPrivilege -> 
appAuths.add(new AppAuths(addPrivilege, "1")));

逻辑其实是一样的,但下面的代码会给人一种高级的感觉(个人认为),性能方面下面的要好很多。
下面是:两个List集合取交集、并集、差集、去重并集的一个简单Demo,可供参考:

package com.ymdd.galaxy.appmanage.core.appauth.service;
 
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
 
 
public class Test {
 
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<String>();
        list1.add("1");
        list1.add("2");
        list1.add("3");
        list1.add("5");
        list1.add("6");
 
        List<String> list2 = new ArrayList<String>();
        list2.add("2");
        list2.add("3");
        list2.add("7");
        list2.add("8");
 
        // 交集
        List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());
        System.out.println("---交集 intersection---");
        intersection.parallelStream().forEach(System.out :: println);
 
        // 差集 (list1 - list2)
        List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
        System.out.println("---差集 reduce1 (list1 - list2)---");
        reduce1.parallelStream().forEach(System.out :: println);
 
        // 差集 (list2 - list1)
        List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());
        System.out.println("---差集 reduce2 (list2 - list1)---");
        reduce2.parallelStream().forEach(System.out :: println);
 
        // 并集
        List<String> listAll = list1.parallelStream().collect(toList());
        List<String> listAll2 = list2.parallelStream().collect(toList());
        listAll.addAll(listAll2);
        System.out.println("---并集 listAll---");
        listAll.parallelStream().forEachOrdered(System.out :: println);
 
        // 去重并集
        List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
        System.out.println("---得到去重并集 listAllDistinct---");
        listAllDistinct.parallelStream().forEachOrdered(System.out :: println);
 
        System.out.println("---原来的List1---");
        list1.parallelStream().forEachOrdered(System.out :: println);
        System.out.println("---原来的List2---");
        list2.parallelStream().forEachOrdered(System.out :: println);
 
    }
}

List之Union(),Intersect(),Except() 即并集,交集,差集运算

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Sample2
{
    class Program
    {
        static void Main(string[] args)
        {
            //List之Union(),Intersect(),Except() 即并集,交集,差集运算
            IList<Student> Students1 = new List<Student>();
            Students1.Add(new Student(1, false, "张三", "深圳"));
            Students1.Add(new Student(2, false, "李四", "广州"));
            Students1.Add(new Student(3, false, "王五", "珠海"));
            Students1.Add(new Student(4, false, "赵六", "东莞"));
 
            IList<Student> Students2 = new List<Student>();
            Students2.Add(new Student(1, false, "张三", "深圳"));
            Students2.Add(new Student(5, false, "李七", "广州"));
            Students2.Add(new Student(6, false, "孙八", "深圳"));
            Students2.Add(new Student(7, true, "赵燕", "深圳"));
 
            //自定义比较规则
            var bingji = Students1.Union(Students2, new StudentListEquality()).ToList();//并集(AB集合所有项)
            var jiaoji = Students1.Intersect(Students2, new StudentListEquality()).ToList();//交集 (AB集合共同项)
            var chaji = Students1.Except(Students2, new StudentListEquality()).ToList();//差集(A集合有,B没有)
 
            Console.WriteLine("以下是并集的结果");
            bingji.ForEach(x =>
            {
                Console.WriteLine(x.Id.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString() + " " + x.Address.ToString());
 
            });
 
            Console.WriteLine("以下是交集的结果");
            jiaoji.ForEach(x =>
            {
                Console.WriteLine(x.Id.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString() + " " + x.Address.ToString());
 
            });
 
            Console.WriteLine("以下是差集的结果");
            chaji.ForEach(x =>
            {
                Console.WriteLine(x.Id.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString() + " " + x.Address.ToString());
 
            });
            Console.ReadKey();
        }
    }
 
    public class Student
    {
        public Student(int id, bool sex, String name, String address)
        {
            this.Id = id;
            this.Sex = sex;
            this.Name = name;
            this.Address = address;
        }
        public int Id { get; set; }
        public bool Sex { get; set; }
        public String Name { get; set; }
        public String Address { get; set; }
 
    }
 
    public class StudentListEquality : IEqualityComparer<Student>
    {
        public bool Equals(Student x, Student y)
        {
            return x.Id == y.Id && x.Name == y.Name && x.Address == y.Address && x.Sex == y.Sex;
        }
        public int GetHashCode(Student obj)
        {
            return (obj == null) ? 0 : obj.ToString().GetHashCode();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值