List 实体中获取 摸个字段的集合
Set<Long> taskIds = orderList.stream().map(EDeliverOrderDO::getTaskId).collect(Collectors.toSet());
List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起:
// list
List<Apple> appleList = new ArrayList<>();//存放apple对象集合
Apple apple1 = new Apple(1,"苹果1",new BigDecimal("3.25"),10);
Apple apple12 = new Apple(1,"苹果2",new BigDecimal("1.35"),20);
Apple apple2 = new Apple(2,"香蕉",new BigDecimal("2.89"),30);
Apple apple3 = new Apple(3,"荔枝",new BigDecimal("9.99"),40);
appleList.add(apple1);
appleList.add(apple12);
appleList.add(apple2);
appleList.add(apple3);
// 分组
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
将list转换map(key和Bean的形式)
Map<String, BazTgTO> tgMap = tgList.stream().collect(Collectors.toMap(BazTgTO::getTgId, n -> n));
将list转换map(key和value是实体的属性)
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName));
将list 根据字段移除对象
// A code block
List list = new ArrayList<>();
list.add(new User(1,"张三"));
list.add(new User(4,"赵六"));
//条件删除
list.removeIf(user -> user.getUserId() == 4);
将list 排序
Collections.sort(personVOList, new Comparator<personVO>() {
public int compare(personVO arg0, personVO arg1) {
return arg0.getUnitCountBegin().compareTo(arg1.getUnitCountBegin());
}
});
list 过滤
// 过滤查询 level 层级为1的
// 第一种写法
List<ArticleClassDO> firstArticleClassList = articleClassDOList.stream().filter(p -> 1 == p.getTreeLevel()).collect(Collectors.toList());
// 第二种写法
List<ArticleClassDO> firstArticleClassList = articleClassDOList.stream().filter(new Predicate<ArticleClassDO>() {
public boolean test(ArticleClassDO articleClassDO) {
return articleClassDO.getTreeLevel() == 1;
}
}).collect(Collectors.toList());
list 过滤 -其中的字段
List<String> levelOneNames = articleList.stream() // 将列表转换为流
.filter(article -> article.getLevel() == 1) // 筛选level为1的元素
.map(ArticleClassDO::getName) // 提取name字段
.collect(Collectors.toList()); // 收集结果为列表
List 实体中获取 摸个字段匹配的一个实体
ImesEventResultVO resultVO = resultVOList.stream()
.filter(vo -> "aaa".equals(vo.getName()))
.findFirst()
.orElse(null);
List 实体中- 根据字段去重
// 首先自定义去重方法,方法公共类方法中
public class CollectionDistinctUtil {
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
ConcurrentHashMap<Object, Boolean> map = new ConcurrentHashMap<>(16);
return t -> map.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE) == null;
}
}
// 调用去重方法处理数据
// 下面用两个字段拼装来去重
personVOList = personVOList.stream().filter(CollectionDistinctUtil.distinctByKey(personVO -> (personVO.getSex()+ personVO.getName()))).collect(Collectors.toList());
List 实体中- 获取字段拼装字符串
如: 获取姓名,拼装成 ‘姓名1,姓名2,姓名3’
// A code block
List list = new ArrayList<>();
list.add(new User(1,"张三"));
list.add(new User(4,"赵六"));
//拼装字符串
String name = list.stream().map(QwContactDO::getName).collect(Collectors.joining(","));