lambda简单案列

package com.kids.demo01.lanbuda;

import com.kids.demo01.entity.user;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//兰姆达表达式
public class lanbuda {

    public static void main(String[] args) {

            List list = new ArrayList<>();
            user u1 = new user();
            u1.setId(1);
            u1.setName("1");
            u1.setPwd("1");
            list.add(u1);

            user u2 = new user();
            u2.setId(2);
            u2.setName("2");
            u2.setPwd("2");
            list.add(u2);

            user u3 = new user();
            u3.setId(3);
            u3.setName("3");
            u3.setPwd("3");
            list.add(u3);


        //list中某一个值--list
        List collect1 = list.stream().map(user::getName).collect(Collectors.toList());
        System.out.println(collect1);


        //list--方法,方法必须是静态的.入参是遍历集合的泛型
        List collect2 = list.stream().map(lanbuda::convert1).collect(Collectors.toList());
        System.out.println(collect2);

        //list--map,根据某一个字段做key,分组
        Map> collect3 = list.stream().collect(Collectors.groupingBy(user::getId, Collectors.toList()));
        System.out.println(collect3);

        //id=2的数据,放到一个集合中
        List collect4 = list.stream().filter(u -> u.getId() == 2).collect(Collectors.toList());
        System.out.println(collect4);


        //list集合中,是否有id=1而且name=1的数据,返回boolean
        Boolean aBoolean = list.stream().filter(u -> u.getId() == 1 && u.getName().equals("1")).findFirst().isPresent();
        boolean bBoolean = list.stream().anyMatch(user -> user.getId() == 1 && user.getName().equals("1"));
        boolean cBoolean = list.stream().allMatch(user -> user.getId() == 1 && user.getName().equals("1"));
        System.out.println(aBoolean);
        System.out.println(bBoolean);
        System.out.println(cBoolean);
    }

    public static user convert1(user u){
        user u4 = new user();
        if(u.getId()==1){
            return null;
        }
        u4.setId(u.getId());
        u4.setName(u.getName());
        u4.setPwd(u.getPwd());
        return u4;
    }
}

 

你可能感兴趣的:(java基础)