java8中的一些lambda操作

先创建一个实体类

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author 宫崎不骏
 * @className Employee
 * @Version 1.0
 * @Description: TODO
 * @date 2020/1/2216:42
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
    private String name;
    private int salary;
    private String office;
}

创建一个main方法

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 宫崎不骏
 * @className ExampleEmployee
 * @Version 1.0
 * @Description: TODO
 * @date 2020/1/2217:12
 */
public class ExampleEmployee {
    private static List<Employee> employeeList = new ArrayList<>();

    static {
        employeeList.add(Employee.builder().name("张三疯").salary(5000).office("郑州").build());
        employeeList.add(Employee.builder().name("张无忌").salary(8000).office("武当山").build());
        employeeList.add(Employee.builder().name("史玉柱").salary(9000).office("上海").build());
        employeeList.add(Employee.builder().name("任正非").salary(4000).office("北京").build());
        employeeList.add(Employee.builder().name("马化腾").salary(66000).office("深圳").build());
        employeeList.add(Employee.builder().name("马云").salary(85000).office("杭州").build());
        employeeList.add(Employee.builder().name("李嘉诚").salary(13000).office("香港").build());
        employeeList.add(Employee.builder().name("小瘪三").salary(23000).office("上海").build());
        employeeList.add(Employee.builder().name("阿三哥").salary(25000).office("上海").build());

    }
    public static void main(String[] args) {

        //anyMatch
        boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("北京"));
        System.out.println("isMatch:"+isMatch);

        //返回所有salary大于6000
        boolean matched = employeeList.stream().allMatch(employee -> employee.getSalary()>6000);
        System.out.println("matched:"+matched);

        //找出工资最高
        Optional<Employee> hightSalary = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
        System.out.println("hightSalary:"+hightSalary);

        //找出工资最低
        Optional<Employee> lowSalary = employeeList.stream().min((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
        System.out.println("lowSalary:"+lowSalary);

        //返回姓名列表
        List<String> names = employeeList.stream().map(employee -> employee.getName()).collect(Collectors.toList());
        System.out.println("names:"+names);

        //返回工资列表
        List<Integer> salarys = employeeList.stream().map(employee -> employee.getSalary()).collect(Collectors.toList());
        System.out.println("salarys:"+salarys);

        //返回office列表
        List<String> offices = employeeList.stream().map(employee -> employee.getOffice()).collect(Collectors.toList());
        System.out.println("offices:"+offices);

        //name List转换成map
        Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
        employeeMap.forEach((key,value)->
                System.out.println(key + "=" + value));

        //salary List转换成map
        Map<Integer,Employee> employeeMapb = employeeList.stream().collect(Collectors.toMap((key->key.getSalary()),(value->value)));
        employeeMapb.forEach((key,value)->
                System.out.println(key + "=" + value));

        //统计办公地址是武当山的个数
        long officeCount = employeeList.stream().filter(employee -> employee.getOffice().equals("武当山")).count();
        System.out.println("officeCount:"+officeCount);

        //统计办公室是上海的个数
        long officeCounts = employeeList.stream().filter(employee -> employee.getOffice().equals("上海")).count();
        System.out.println("统计办公室是上海的个数:"+officeCounts);

        //List转换为set
        Set<String> officeSet = employeeList.stream().map(employee -> employee.getOffice()).distinct().collect(Collectors.toSet());
        System.out.println("officeSet:"+officeSet);
        Set<Integer> officeSets = employeeList.stream().map(employee -> employee.getSalary()).distinct().collect(Collectors.toSet());
        System.out.println("officeSet:"+officeSets);
        Set<String> officeSeta = employeeList.stream().map(employee -> employee.getName()).distinct().collect(Collectors.toSet());
        System.out.println("officeSet:"+officeSeta);

        //查找办公地址是上海的员工
        Optional<Employee> addressofice = employeeList.stream().filter(employee -> employee.getOffice().equals("上海")).findAny();
        System.out.println("查找办公地址是上海的员工:"+addressofice);

        //按照工资的降序来列出员工信息
        List<Employee> wagesdrop = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
        System.out.println("按照工资的降序来列出员工信息:"+wagesdrop);

        //按照名字的升序来列出员工信息
        List<Employee> namerise = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
        System.out.println("按照名字的升序来列出员工信息:"+namerise);

        //获取工资最高的前2条员工信息
        List<Employee> topTwo = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary()))
                .limit(2).collect(Collectors.toList());
        System.out.println("获取工资最高的前2条员工信息:"+topTwo);

        //获取平均工资
        OptionalDouble averageSalary = employeeList.stream().mapToInt(employee->employee.getSalary()).average();
        System.out.println("平均工资:"+averageSalary);

        //查找上海
        OptionalDouble averagesAlaryByOffice = employeeList.stream().filter(employee -> employee.getOffice().equals("上海"))
                .mapToInt(employee->employee.getSalary()).average();
        System.out.println("上海办公室平均工资:"+averagesAlaryByOffice);
    }
}

控制台总要输出点东西吧!

isMatch:true
matched:false
hightSalary:Optional[Employee(name=马云, salary=85000, office=杭州)]
lowSalary:Optional[Employee(name=任正非, salary=4000, office=北京)]
names:[张三疯, 张无忌, 史玉柱, 任正非, 马化腾, 马云, 李嘉诚, 小瘪三, 阿三哥]
salarys:[5000, 8000, 9000, 4000, 66000, 85000, 13000, 23000, 25000]
offices:[郑州, 武当山, 上海, 北京, 深圳, 杭州, 香港, 上海, 上海]
任正非=Employee(name=任正非, salary=4000, office=北京)
李嘉诚=Employee(name=李嘉诚, salary=13000, office=香港)
史玉柱=Employee(name=史玉柱, salary=9000, office=上海)
阿三哥=Employee(name=阿三哥, salary=25000, office=上海)
小瘪三=Employee(name=小瘪三, salary=23000, office=上海)
马云=Employee(name=马云, salary=85000, office=杭州)
张三疯=Employee(name=张三疯, salary=5000, office=郑州)
马化腾=Employee(name=马化腾, salary=66000, office=深圳)
张无忌=Employee(name=张无忌, salary=8000, office=武当山)
4000=Employee(name=任正非, salary=4000, office=北京)
8000=Employee(name=张无忌, salary=8000, office=武当山)
66000=Employee(name=马化腾, salary=66000, office=深圳)
25000=Employee(name=阿三哥, salary=25000, office=上海)
23000=Employee(name=小瘪三, salary=23000, office=上海)
13000=Employee(name=李嘉诚, salary=13000, office=香港)
9000=Employee(name=史玉柱, salary=9000, office=上海)
5000=Employee(name=张三疯, salary=5000, office=郑州)
85000=Employee(name=马云, salary=85000, office=杭州)
officeCount:1
统计办公室是上海的个数:3
officeSet:[上海, 香港, 武当山, 郑州, 杭州, 北京, 深圳]
officeSet:[8000, 4000, 66000, 5000, 9000, 13000, 23000, 25000, 85000]
officeSet:[任正非, 李嘉诚, 史玉柱, 马云, 小瘪三, 阿三哥, 张三疯, 马化腾, 张无忌]
查找办公地址是上海的员工:Optional[Employee(name=史玉柱, salary=9000, office=上海)]
按照工资的降序来列出员工信息:[Employee(name=马云, salary=85000, office=杭州), Employee(name=马化腾, salary=66000, office=深圳), Employee(name=阿三哥, salary=25000, office=上海), Employee(name=小瘪三, salary=23000, office=上海), Employee(name=李嘉诚, salary=13000, office=香港), Employee(name=史玉柱, salary=9000, office=上海), Employee(name=张无忌, salary=8000, office=武当山), Employee(name=张三疯, salary=5000, office=郑州), Employee(name=任正非, salary=4000, office=北京)]
按照名字的升序来列出员工信息:[Employee(name=任正非, salary=4000, office=北京), Employee(name=史玉柱, salary=9000, office=上海), Employee(name=小瘪三, salary=23000, office=上海), Employee(name=张三疯, salary=5000, office=郑州), Employee(name=张无忌, salary=8000, office=武当山), Employee(name=李嘉诚, salary=13000, office=香港), Employee(name=阿三哥, salary=25000, office=上海), Employee(name=马云, salary=85000, office=杭州), Employee(name=马化腾, salary=66000, office=深圳)]
获取工资最高的前2条员工信息:[Employee(name=马云, salary=85000, office=杭州), Employee(name=马化腾, salary=66000, office=深圳)]
平均工资:OptionalDouble[26444.444444444445]
上海办公室平均工资:OptionalDouble[19000.0]

再写一个测试类

import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 宫崎不骏
 * @className EmployeeTest
 * @Version 1.0
 * @Description: TODO
 * @date 2020/1/2220:12
 */
public class EmployeeTest {
    public static List<Employee> generateData() {
        return Arrays.asList(new Employee("Matt", 5000, "New York"),
                new Employee("Steve", 6000, "London"),
                new Employee("Carrie", 10000, "New York"),
                new Employee("Peter", 7000, "New York"),
                new Employee("Alec", 6000, "London"),
                new Employee("Sarah", 8000, "London"),
                new Employee("Rebecca", 4000, "New York"),
                new Employee("Pat", 20000, "New York"),
                new Employee("Tammy", 9000, "New York"),
                new Employee("Fred", 15000, "Tokyo"));
    }

    public static Map<String, Integer> generateMapData() {
        Map<String, Integer> items = new HashMap<>();
        items.put("A", 10);
        items.put("B", 20);
        items.put("C", 30);
        items.put("D", 40);
        items.put("E", 50);
        items.put("F", 60);

        return items;
    }

    @Test
    public void testEmployee(){
        List<Employee> results = generateData();

        //打印出名字是Strve的员工信息
        results.forEach(c->{
            if (c.getName().equals("Steve")){
                System.out.println("打印出名字是Strve的员工信息:"+c);
            }
        });
        System.out.println("----------I'm the divider----------");

        //找出年薪超过6000的员工
        results.stream().filter(c -> c.getSalary() >= 6000).forEach(
                c -> System.out.println("年薪>=6000的员工有"+c));

        System.out.println("----------I'm the divider----------");

        //java8遍历map
        Map<String, Integer> map = generateMapData();
        map.forEach((key,value)->
                System.out.println("key:"+key+","+"value:"+value));

        System.out.println("----------I'm the divider----------");

        //java8 分组操作
        Map<String,List<Employee>> groupMap = results.stream().collect(Collectors.groupingBy(c -> c.getOffice()));
        System.out.println("groupMap:"+groupMap);

        System.out.println("----------I'm the divider----------");

        //List转化map
        Map<String,Object> map_ = results.stream().collect(Collectors.toMap(Employee::getName,Employee::getOffice));
        map_.forEach((key, value) ->
                System.out.println("key:"+key+","+"value:"+value));

        System.out.println("----------I'm the divider----------^-^");
        /**
         * 注意  java8 stream 的toMap方法,如果key有重复的就会跑出 Exception in thread "main" java.lang.IllegalStateException: Duplicate key 的异常
         * 原因map集合key是唯一的,有多个重复的key
         * 原始方法如下: Map<Integer,Employee> employeeMap = results.stream().collect(Collectors.toMap((key -> key.getSalary()),(value -> value)));
         * 改进方法如下: Map<Integer,Employee> employeeMap = results.stream().collect(Collectors.toMap((key -> key.getSalary()),(value -> value),(e1,e2) -> e1));
         * 改进方法只取了相同key信息的第一条,也就是e1。
         **/
        Map<Integer,Employee> employeeMap = results.stream().collect(Collectors.toMap((key -> key.getSalary()),(value -> value),(e1,e2) -> e1));
        employeeMap.forEach((key,value) ->
                System.out.println(key+","+value));

        System.out.println("----------I'm the divider----------^-^");
        //打印出值大于30的map
        Map<String,Integer> resultMap = map.entrySet().stream().filter(c -> c.getValue() > 30).collect(Collectors.toMap(p -> p.getKey(),p -> p.getValue()));
        resultMap.forEach((key,value) ->
                System.out.println(key + "=" + value));

        System.out.println("----------I'm the divider----------^-^");
        //打印key=D的map
        Map<String,Integer> mapResults = map.entrySet().stream().filter(c -> c.getKey().equals("D")).collect(Collectors.toMap(p -> p.getKey(),p -> p.getValue()));
        mapResults.forEach((key,value) -> System.out.println(key + ">>>" + value));

        System.out.println("----------I'm the divider----------^-^");
        Optional<String> optional = Optional.of("李海潮吃屁");
        System.out.println(optional.isPresent());


    }
    @Test
    public void testEmployeeExample() {
        //anyMatch
        List<Employee> employeeList = generateData();
        boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
        System.out.println("isMatch:"+isMatch);

        //allMatch
        boolean matched = employeeList.stream().allMatch(employee -> employee.getOffice().equals("London"));
        System.out.println(matched);

        //找出工资最高的
        Optional<Employee> employeeOptional = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
        System.out.println(employeeOptional);

        //找出工资最少的
        Optional<Employee> employee = employeeList.stream().min((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
        System.out.println(employee);

        //返回姓名列表
        List<String> names = employeeList.stream().map(c->c.getName()).collect(Collectors.toList());
        System.out.println(names);

        System.out.println(">>>>>>>>>>>");
        //List转化Map
        Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
        employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));

        //统计办公室是New York的个数
        long officeCount =  employeeList.stream().filter(c->c.getOffice().equals("New York")).count();
        System.out.println(officeCount);

        long salaryCount = employeeList.stream().filter(c->c.getSalary()>60000).count();
        System.out.println(salaryCount);

        //List转化为Set
        Set<String> officeSet = employeeList.stream().map(c->c.getOffice()).distinct().collect(Collectors.toSet());
        System.out.println(officeSet);

        Set<Integer> salarySet = employeeList.stream().map(c->c.getSalary()).distinct().collect(Collectors.toSet());
        System.out.println(salarySet);

        //查找办公室地点是New York的员工
        Optional<Employee> optionals = employeeList.stream().filter(c->c.getOffice().equals("New York")).findAny();
        System.out.println(optionals);

        System.out.println(">>>>>工资降序排序>>>>>");
        //按照工资的降序来列出员工信息
        List<Employee> sortSalaryEmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
        System.out.println(sortSalaryEmployeeList);

        System.out.println(">>>>>姓名升序排序>>>>>");
        List<Employee> sortNameEmployeeList = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
        System.out.println(sortNameEmployeeList);

        System.out.println(">>>>获取工资最高的前2条员工信息");
        List<Employee> dispaly2EmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).limit(2).collect(Collectors.toList());
        System.out.println(dispaly2EmployeeList);

        System.out.println(">>>>获取平均工资");
        OptionalDouble averageSalary = employeeList.stream().mapToInt(c->c.getSalary()).average();
        System.out.println(averageSalary);

        System.out.println(">>>>获取工作地点的平均工资");
        OptionalDouble optionalDouble = employeeList.stream().filter(c->c.getOffice().equals("New York")).mapToInt(c->c.getSalary()).average();
        System.out.println(optionalDouble);

        System.out.println(">>>>>>Java8 Optional用法>>>>>>");
        Optional<String> stringOptional = Optional.of("test");
        System.out.println(stringOptional.get());

        Optional<String> isOptional = Optional.ofNullable("hello");
        System.out.println(isOptional.isPresent());
        System.out.println(isOptional.get());
        System.out.println(isOptional.orElse("0"));

        System.out.println(">>>>>>>>>>>>");
        //Optional<String> optionalVal = Optional.of(null);
        // System.out.println(optionalVal);
        Optional<String> optional = Optional.ofNullable("optional");
        System.out.println(optional);
        System.out.println(optional.isPresent());
        System.out.println(optional.get());
        System.out.println(optional.orElse("haha"));
        System.out.println(">>>>>>>>>>>>");

        Optional<Employee> employeeOptional_ = employeeList.stream().filter(c->c.getOffice().equals("New York")).findFirst();
        System.out.println(employeeOptional_);

    }



}

输出点东西吧

testEmployee

打印出名字是Strve的员工信息:Employee(name=Steve, salary=6000, office=London)
----------I'm the divider----------
年薪>=6000的员工有Employee(name=Steve, salary=6000, office=London)
年薪>=6000的员工有Employee(name=Carrie, salary=10000, office=New York)
年薪>=6000的员工有Employee(name=Peter, salary=7000, office=New York)
年薪>=6000的员工有Employee(name=Alec, salary=6000, office=London)
年薪>=6000的员工有Employee(name=Sarah, salary=8000, office=London)
年薪>=6000的员工有Employee(name=Pat, salary=20000, office=New York)
年薪>=6000的员工有Employee(name=Tammy, salary=9000, office=New York)
年薪>=6000的员工有Employee(name=Fred, salary=15000, office=Tokyo)
----------I'm the divider----------
key:A,value:10
key:B,value:20
key:C,value:30
key:D,value:40
key:E,value:50
key:F,value:60
----------I'm the divider----------
groupMap:{New York=[Employee(name=Matt, salary=5000, office=New York), Employee(name=Carrie, salary=10000, office=New York), Employee(name=Peter, salary=7000, office=New York), Employee(name=Rebecca, salary=4000, office=New York), Employee(name=Pat, salary=20000, office=New York), Employee(name=Tammy, salary=9000, office=New York)], Tokyo=[Employee(name=Fred, salary=15000, office=Tokyo)], London=[Employee(name=Steve, salary=6000, office=London), Employee(name=Alec, salary=6000, office=London), Employee(name=Sarah, salary=8000, office=London)]}
----------I'm the divider----------
key:Matt,value:New York
key:Tammy,value:New York
key:Pat,value:New York
key:Sarah,value:London
key:Steve,value:London
key:Alec,value:London
key:Rebecca,value:New York
key:Fred,value:Tokyo
key:Peter,value:New York
key:Carrie,value:New York
----------I'm the divider----------^-^
20000,Employee(name=Pat, salary=20000, office=New York)
4000,Employee(name=Rebecca, salary=4000, office=New York)
8000,Employee(name=Sarah, salary=8000, office=London)
10000,Employee(name=Carrie, salary=10000, office=New York)
6000,Employee(name=Steve, salary=6000, office=London)
15000,Employee(name=Fred, salary=15000, office=Tokyo)
9000,Employee(name=Tammy, salary=9000, office=New York)
7000,Employee(name=Peter, salary=7000, office=New York)
5000,Employee(name=Matt, salary=5000, office=New York)
----------I'm the divider----------^-^
D=40
E=50
F=60
----------I'm the divider----------^-^
D>>>40
----------I'm the divider----------^-^
true

testEmployeeExample

isMatch:true
false
Optional[Employee(name=Pat, salary=20000, office=New York)]
Optional[Employee(name=Rebecca, salary=4000, office=New York)]
[Matt, Steve, Carrie, Peter, Alec, Sarah, Rebecca, Pat, Tammy, Fred]
>>>>>>>>>>>
Matt=Employee(name=Matt, salary=5000, office=New York)
Tammy=Employee(name=Tammy, salary=9000, office=New York)
Pat=Employee(name=Pat, salary=20000, office=New York)
Sarah=Employee(name=Sarah, salary=8000, office=London)
Steve=Employee(name=Steve, salary=6000, office=London)
Alec=Employee(name=Alec, salary=6000, office=London)
Rebecca=Employee(name=Rebecca, salary=4000, office=New York)
Fred=Employee(name=Fred, salary=15000, office=Tokyo)
Peter=Employee(name=Peter, salary=7000, office=New York)
Carrie=Employee(name=Carrie, salary=10000, office=New York)
6
0
[New York, Tokyo, London]
[6000, 10000, 8000, 4000, 20000, 5000, 7000, 9000, 15000]
Optional[Employee(name=Matt, salary=5000, office=New York)]
>>>>>工资降序排序>>>>>
[Employee(name=Pat, salary=20000, office=New York), Employee(name=Fred, salary=15000, office=Tokyo), Employee(name=Carrie, salary=10000, office=New York), Employee(name=Tammy, salary=9000, office=New York), Employee(name=Sarah, salary=8000, office=London), Employee(name=Peter, salary=7000, office=New York), Employee(name=Steve, salary=6000, office=London), Employee(name=Alec, salary=6000, office=London), Employee(name=Matt, salary=5000, office=New York), Employee(name=Rebecca, salary=4000, office=New York)]
>>>>>姓名升序排序>>>>>
[Employee(name=Alec, salary=6000, office=London), Employee(name=Carrie, salary=10000, office=New York), Employee(name=Fred, salary=15000, office=Tokyo), Employee(name=Matt, salary=5000, office=New York), Employee(name=Pat, salary=20000, office=New York), Employee(name=Peter, salary=7000, office=New York), Employee(name=Rebecca, salary=4000, office=New York), Employee(name=Sarah, salary=8000, office=London), Employee(name=Steve, salary=6000, office=London), Employee(name=Tammy, salary=9000, office=New York)]
>>>>获取工资最高的前2条员工信息
[Employee(name=Pat, salary=20000, office=New York), Employee(name=Fred, salary=15000, office=Tokyo)]
>>>>获取平均工资
OptionalDouble[9000.0]
>>>>获取工作地点的平均工资
OptionalDouble[9166.666666666666]
>>>>>>Java8 Optional用法>>>>>>
test
true
hello
hello
>>>>>>>>>>>>
Optional[optional]
true
optional
optional
>>>>>>>>>>>>
Optional[Employee(name=Matt, salary=5000, office=New York)]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值