在获取的对象的name字段都通过smpil拼接成一个String
String concatenatedNames = personList.stream()
.map(Person::getName)
.collect(Collectors.joining(", "));
倒序
List<String> newList = personList.stream()
.sorted(Comparator.comparing(Person::getSalary).reversed())
.map(Person::getName)
.collect(Collectors.toList());
分组
Map<String, List<Person>> group = personList.stream()
.collect(Collectors.groupingBy(Person::getSex));
案例
public class EmployeeData {
public static List<Employee> getEmployees(){
List<Employee> list = new ArrayList<>();
list.add(new Employee(1001, "马化腾", 34, 6000.38));
list.add(new Employee(1002, "马云", 2, 19876.12));
list.add(new Employee(1003, "刘强东", 33, 3000.82));
list.add(new Employee(1004, "雷军", 26, 7657.37));
list.add(new Employee(1005, "李彦宏", 65, 5555.32));
list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
list.add(new Employee(1006, "比尔盖茨2", 42, 9500.43));
list.add(new Employee(1007, "任正非", 26, 4333.32));
list.add(new Employee(1008, "扎克伯格军", 35, 2500.32));
return list;
}
public static void main(String[] args) {
List<Employee> list = EmployeeData.getEmployees();
// 判断这个对象全部一样才去重(id也一样才去重),要么对摸个字段去重
list.stream().distinct().forEach(System.out::println);
// 获取名称包含比的去重
list.stream().map(Employee::getName).filter(x -> x.contains("比")).distinct().forEach(System.out::println);
// 过滤姓名长度为超过3的
list.stream().filter(name -> name.getName().length() > 3).forEach(System.out::println);
// 根据年龄字段倒叙
list.stream().sorted((e1,e2) -> e2.getAge() - e1.getAge()).forEach(System.out::println);
// 练习:是否存在员工的工资大于 10000
boolean b = list.stream().anyMatch(emp -> emp.getSalary() > 100000);
// 练习:返回最高工资的员工
Employee employee = list.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())).orElse(null);
}
}
stream里面new对象
List<Conditions> collect = dto.getConditions().stream().map(x -> {
Conditions conditions = new Conditions();
conditions.setName(x.getName());
conditions.setThreshold(x.getThreshold());
conditions.setWeight(x.getWeight());
return conditions;
}).collect(Collectors.toList());
tSetRules.setConditions(collect);
生成map集合
Map<String, String> info = list.stream().collect(Collectors.toMap(
TAddresExcel::getAddresName,
TAddresExcel::getAddresCode));