JAVA8常用stream处理方法

发布时间:2024年01月24日

1、获取字段集合

List<String> ids= list.stream().map(Bean::getId).collect(Collectors.toList());

2、list转map,1对多

Map<String, List<Bean>> beanMap= list.stream().collect(Collectors.groupingBy(Bean::getId));

?3、list转map,1对1

Map<String, Bean> beanMap= list.stream().collect(Collectors.toMap(Bean::getId, p -> p, (f1, f2) -> f1));

4、排序

//倒序
List<Bean> reslist = list.stream().sorted(Comparator.comparing(Bean::getCreateDate, Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
//正序
List<Bean> reslist = list.stream().sorted(Comparator.comparing(Bean::getCreateDate, Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());
//多字段排序
List<Bean> reslist = list.stream().sorted(Comparator.comparing(Bean::Id).thenComparing(Bean::getColumnNo)).collect(Collectors.toList());

5、过滤

List<Bean> reslist= list.stream().filter(e->'张三'.equals(e.getName())).collect(Collectors.toList()) ;

6、获取第一个

Optional<Bean> first = list.stream().filter(p -> '男'.equals(p.getSex())).findFirst();

 if (first.isPresent()) {
//获取值
     Bean f = first.get();
}

7、求和

BigDecimal sumPayAmt = list.stream().filter(p->p.getTrdAmt()!=null).map(Bean::getTrdAmt).reduce(BigDecimal.ZERO, BigDecimal::add);

Integer total = list.stream().collect(Collectors.summingInt(Bean::getCnt));

8、最大值或者最小值

Bean one = list.stream().max(Comparator.comparing(Bean::getId)).get();
Bean one = list.stream().min(Comparator.comparing(Bean::getId)).get();

9、分割list

/**
	 * 分割list
	 * @param collection
	 * @param <T>
	 * @return
	 */
	public static <T> List<List<T>> splitList(List<T> collection) {
		if(CollectionUtils.isEmpty(collection)) {
			return Collections.emptyList();
		}
		int splitSize = 1000;
		// 计算分割后的大小
		int maxSize = (collection.size() + splitSize - 1) / splitSize;
		return Stream.iterate(0, f -> f + 1)
				.limit(maxSize).parallel()
				.map(a -> collection.parallelStream().skip(a * splitSize).limit(splitSize).collect(Collectors.toList()))
				.filter(b -> !b.isEmpty()).collect(Collectors.toList());
	}

10、去重

List<String> cpIdList = reqParams.getCpIdList().stream().distinct().collect(Collectors.toList()) ;
//直接转set
Set<String> cpIdList = reqParams.getCpIdList().stream().collect(Collectors.toSet()) ;

11、list转新的list

List<Bean> resList= list.stream().map(e->{
				Bean bean = new Bean();
				bean.setKey(e.getKey());
				bean.setValue(e.getValue());
				return temp;
			}).collect(Collectors.toList());

12、只取对象的两个属性转map

Map<String,String> map = list.stream().collect(
					Collectors.toMap(Bean::getName(), Bean::getSex, (v1, v2) -> v1));

13、取对象的某个属性转数组

String[] to = list.stream().map(Bean::getEmail).toArray(String[]::new);

14、取固定数量的list

list =list.stream().limit(10).collect(Collectors.toList());

文章来源:https://blog.csdn.net/ysnluoning/article/details/135763541
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。