Stream操作List集合

在获取的对象的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));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值