stream常用方法

下面为一个普通的实体类

static class Employee{
		private Long empno;
		private String name;
		private Integer salary;
		private Integer deptno;

	public Long getEmpno() {
		return empno;
	}

	public void setEmpno(Long empno) {
		this.empno = empno;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getSalary() {
		return salary;
	}

	public void setSalary(Integer salary) {
		this.salary = salary;
	}

	public Integer getDeptno() {
		return deptno;
	}

	public void setDeptno(Integer deptno) {
		this.deptno = deptno;
	}

	public Employee(long l, String smith, int i, int i1) {
	}

--------------------------------------------------------------------------------------
常用方法

Employee e1 = new Employee(7369L, "SMITH", 800, 20);
		Employee e2 = new Employee(7499L, "ALLEN", 1600, 30);
		Employee e3 = new Employee(7521L, "WARD", 1250, 30);
		Employee e4 = new Employee(7782L, "CLARK", 2450, 10);
		Employee e5 = new Employee(7876L, "ADAMS", 1100, 20);
		List<Employee> employees = Arrays.asList(e1, e2, e3, e4, e5);
		//取某列
		List<String> nameList = employees.stream().map(employee -> employee.getName()).collect(Collectors.toList());
		//求和
		int sum = employees.stream().mapToInt(employee -> employee.getDeptno()).sum();
		//过滤
		List<Employee> newList = employees.stream().filter(employee -> employee.getDeptno() > 1500).collect(Collectors.toList());
		//排序-由低到高
		List<Employee> newList3 = employees.stream().sorted(Comparator.comparing(Employee::getDeptno)).collect(Collectors.toList());
		//归约 转成集合元素或聚合元素
		//按员工部门号进行分类
		Map<Integer,List<Employee>> map = employees.stream().collect(Collectors.groupingBy(Employee::getDeptno));
		for (Map.Entry<Integer,List<Employee>> entry : map.entrySet()){
			System.out.print("key = " + entry.getKey() + ", value = " + entry.getValue());
		}
		//获取员工姓名,用,进行拼接
		employees.stream().map(employee -> employee.getName()).collect(Collectors.joining(","));
		//获取20部门员工姓名,按薪水由高到低排序
		List<String> new3 = employees.stream().filter(employee -> employee.getDeptno().equals("20")).sorted(Comparator.comparing(Employee::getSalary).reversed()).map(employee -> employee.getName()).collect(Collectors.toList());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值