Java8 stream/lambda 便捷用法

1、过滤

List<Condition> type1 = conditionsList.stream().filter(item -> item.getSortType() == 1).collect(Collectors.toList());

过滤出符合条件的元素,作为一个新的list

2、删除集合中的元素

changeFields.removeIf(changeField -> changeField.getId() == 36);

删除集合changeFields中ID为36的元素,相比于for循环和迭代器,这种删除方式快捷方便的多

3、合并两个同类型的list

Stream.of(dto1, dto2).flatMap(Collection::stream).collect(Collectors.toList());

合并同类项的两个list,返回一个新的list;等同于list.addAll()方法,上面这个方法更便捷而已

4、获取集合中的元素的属性(字段值)

List<String> customerIdList = labelList.stream().map(LabelSynchronizeDTO::getCustomerId).collect(Collectors.toList());

上面这行代码,获取的是List集合当中的CustomerId属性,最后返回List集合

5、根据元素属性,合并两个集合

## 伪码演示
class record{
	private String customerId;
	
	private String A;
	
	private String B;
}

recordList = record1.stream().peek(m -> record2.stream().filter(m2-> Objects.equals(m.getCustomerId(),m2.getCustomerId())).forEach(m2-> {
            m.setB(m2.getB());
        })).collect(Collectors.toList());

这个方法应用场景感觉不多,上面代码的意思大致为,有两个集合1,2;集合1,2当中元素的ID是相同的,根据ID合并两个集合,最终得到的集合,其中元素的属性A取得是集合1,属性B取得是集合2

posted @ 2022-05-25 14:07  棒棒糖堂堂主  阅读(95)  评论(0)    收藏  举报