当前位置: 首页>后端>正文

Stream流获取

Stream流获取,第1张
Stream流获取,第2张
Stream流获取,第3张

package unit6;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.stream.Collectors;

public class Stream03 {

public static void main(String[] args) {

List<Employee> list = new ArrayList<>();

Employee ceo = new Employee("张三", 56, "男", 50000.42D, "浙江杭州", "浙江杭州", "ceo", null);

Employee manager1 = new Employee("李四", 47, "女", 20000.7D, "浙江宁波", "浙江宁波", "经理", ceo);

Employee manager2 = new Employee("王五", 45, "男", 24000.5D, "浙江金华", "浙江金华", "经理", ceo);

Employee employee1 = new Employee("麻六", 27, "女", 7000.6D, "浙江宁波", "广东广州", "售前", manager1);

Employee employee2 = new Employee("孙七", 28, "男", 8000.8D, "浙江宁波", "广东深圳", "售后", manager1);

Employee employee3 = new Employee("赵八", 27, "女", 9500.2D, "浙江杭州", "云南昆明", "售前", manager2);

Employee employee4 = new Employee("钱九", 26, "男", 9000.0D, "浙江杭州", "云南玉溪", "售后", manager2);

list.add(ceo);

list.add(manager1);

list.add(manager2);

list.add(employee1);

list.add(employee2);

list.add(employee3);

list.add(employee4);

// (3)Stream流获取

// collect

// (1)分组:Collectors.groupingBy

Map<String, List<Employee>> collectGroup = list.stream().collect(Collectors.groupingBy(employee -> employee.getPosition()));

collectGroup.forEach((k,v)->{

System.out.println(k + "\t" + v);

});

// (2)list->set:Collectors.toSet()

Set<Employee> collectSet = list.stream().collect(Collectors.toSet());

collectSet.forEach(System.out::println);

// (3)list->map:Collectors.toMap

Map<String, Employee> collectMap = list.stream().collect(Collectors.toMap(Employee::getName, Employee->Employee));

collectMap.forEach((k,v)->{

System.out.println(k + "\t" + v);

});

// (4)平均:Collectors.averagingDouble()

Double collectDouble = list.stream().collect(Collectors.averagingDouble(Employee::getSalary));

System.out.println(collectDouble);

}

}


https://www.xamrdz.com/backend/3up1936673.html

相关文章: