java 之 使用stream判断两个list元素的属性并输出

/**
* 使用stream判断两个list中元素不同的item
*/
@Test
public void test1(){
List<Param> stringList1 = new LinkedList<Param>(){{
    add(new Param(1,"1111"));
    add(new Param(2, "2222"));
    add(new Param(3, "3333"));
}};

List<Param> stringList2 = new LinkedList<Param>(){{
    add(new Param(1,"1111"));
    add(new Param(2, "4444"));
    add(new Param(3, "5555"));
}};

// 判断key相同,value相同的元素
Map<Integer, String> tmpList2 = stringList2.stream().collect(Collectors.toMap(Param::getId, Param::getName));
var tmplist = stringList1.stream().filter(item -> (tmpList2.get(item.getId()) != null && tmpList2.get(item.getId()).equals(item.getName()))).collect(Collectors.toList());
System.out.println(tmplist);
}


@Setter
@Getter
@ToString
@AllArgsConstructor
public static class Param{
private Integer id;
private String name;
}
/**
 * 使用stream判断两个list中元素不同的item
 */
@Test
public void test1(){
    List<Param> stringList1 = new LinkedList<Param>(){{
        add(new Param(1,"1111", "b"));
        add(new Param(2, "2222", "c"));
        add(new Param(3, "3333", "a"));
    }};

    List<Param> stringList2 = new LinkedList<Param>(){{
        add(new Param(1,"1111", "c"));
        add(new Param(2, "4444", "b"));
        add(new Param(3, "5555", "a"));
    }};

   // 判断key相同,value相同的元素
   Map<Integer, String> tmpList2 = stringList2.stream().collect(Collectors.toMap(Param::getId, Param::getName));
   var tmplist = stringList1.stream().filter(item -> (tmpList2.get(item.getId()) != null && tmpList2.get(item.getId()).equals(item.getName()))).collect(Collectors.toList());
   System.out.println(tmplist);

   // 如果需要判断多个值,直接将对象加入进去
   Map<Integer, Param> tmpList3 = stringList2.stream().collect(Collectors.toMap(Param::getId, Function.identity()));
   var tmplist2 = stringList1.stream().filter(item -> (tmpList3.get(item.getId()) != null && tmpList3.get(item.getId()).getType().equals(item.getType()))).collect(Collectors.toList());
   System.out.println(tmplist2);
}


@Setter
@Getter
@ToString
@AllArgsConstructor
@EqualsAndHashCode
public static class Param{
    private Integer id;
    private String name;
    private String type;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值