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)]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章