JDK1.8 Stream流使用

​​​​​​​

一、概述

JDK1.8新增加流接口:java.util.stream.Stream。

所有集合Collection都可以使用 stream的默认方法获取流;获取数组对应的流,可以使用Stream接口的静态方法of。

二、Stream流的常用方法:filter、map、forEach、count、skip、limit、concat、sorted

java 复制代码
    @Test
	public void contextLoads() {
		List<User> list = buildUserList();
		  //list.forEach(System.out::println);
		//用map:把流中的元素映射到另一个流中,返回一个新的列表
		List<String> idList = list.stream().map(user -> {return user.getId();}).collect(Collectors.toList());
		System.out.println(JSON.toJSONString(idList));
		List<String> nameList = list.stream().map(user -> {return user.getName();}).collect(Collectors.toList());
		System.out.println(JSON.toJSONString(nameList));
        //过滤:filter,根据返回Boolean决定返回结果,返回一个新的列表
		List<User> uList = list.stream().filter(user -> user.getId().startsWith("A01")).collect(Collectors.toList());
		System.out.println(JSON.toJSONString(uList));
        //分页操作,从第2页开始取2条数据
		uList = list.stream().skip(1*2).limit(2).collect(Collectors.toList());
		System.out.println("分页::"+JSON.toJSONString(uList));
        //升序
		List<User> user_list = list.stream().sorted(Comparator.comparing(User::getId)).collect(Collectors.toList());
		System.out.println("升序排序::"+JSON.toJSONString(user_list));
		//降序
		user_list = list.stream().sorted(Comparator.comparing(User::getId).reversed()).collect(Collectors.toList());
		System.out.println("降序排序::"+JSON.toJSONString(user_list));
		//统计集合元素总数
		long count = list.stream().count();
		System.out.println("集合总数::"+count);
		//两个集合合并
		List<String> id_name_list=Stream.concat(idList.stream(),nameList.stream()).collect(Collectors.toList());
		System.out.println("列表合并::"+JSON.toJSONString(id_name_list));
	}
	
	private List<User> buildUserList(){
		List<User> list = new ArrayList<>();
		User user = null;
		for (int i=10;i<30;i++) {
			user = new User();
			user.setId("A0"+i);
			user.setName("ABD"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
			list.add(user);
		}

		return list;
	}
相关推荐
无所谓^_^1 分钟前
个人健康管理系统 | Springboot3 | Vue3
java·vue·毕业设计·springboot·课程设计·毕设·前后端分离
杨凯凡8 分钟前
Spring Boot 的 @Transactional 为什么会失效?从代理、自调用到异常回滚的排查实战
java·spring boot·spring·事务·后端开发
曼岛_23 分钟前
[图解密码学]第5章 对称加密基础
java·数据库·密码学
天河归来10 小时前
第三方接口不稳定,如何让核心任务继续完成
java·大数据
Knight_AL11 小时前
Java 文件下载时文件名中的 `#` 被转换成 `%23`?一次 URL 编码与解码问题排查
java·开发语言
砚底藏山河12 小时前
python量化自定义周期 K 线合成
java·开发语言·数据库·python·金融
猿究院_夏燊13 小时前
MySQL 的四种隔离级别
java·数据库·mysql
码流子13 小时前
移动收费怎么做?手持终端+App+收费中心的架构实践
java·开发语言·架构
霸道流氓气质14 小时前
AI 流式对话与实时聊天平台:SSE 解码竞态、有状态会话隔离与背压取消的 Vue3 + Spring AI 生产级实战
java·人工智能·spring
云创智城-yuncitys14 小时前
YunParking 4.0:JDK 17 与 Spring Boot 3.2 的停车云升级
java·开发语言·spring boot