Stream系列(一) Filter方法使用

Filter是過濾器,也能夠當查詢使用java

EmployeeTestCase.javacode

package com.example.demo;

import lombok.extern.log4j.Log4j2;
import org.junit.Test;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@Log4j2
public class EmployeeTestCase extends BaseTest{
    @Test
    public void filter() {
        //獲取包含Alex員工列表
        List<Employee> employeeIs1 = list.stream().filter(e -> e.getName().contains("Alex")).collect(Collectors.toList());
        assertTrue(null != employeeIs1 && employeeIs1.get(0).getId() == 1l);
        //獲取包含Jacks名稱的首位員工
        Optional<Employee> employeeJaskFirst2 = list.stream().filter(e -> e.getName().contains("Jack")).findFirst();
        assertEquals(employeeJaskFirst2.get().getId(), 3);
        //獲取全部薪酬爲1500的員工
        List<Employee> employees1350 = list.stream().filter(employee -> employee.getSalary() == 1500).peek(System.out::println).collect(Collectors.toList());
        assertEquals(2, employees1350.size());
    }
}

BaseTest.javaget

package com.example.demo;

import java.util.Arrays;
import java.util.List;

public class BaseTest {
    protected static final List<Employee> list = Arrays.asList(
            new Employee(1, "Alex", 1000),
            new Employee(2, "Michael", 2000),
            new Employee(3, "Jack", 1500),
            new Employee(4, "Owen", 1500),
            new Employee(5, "Denny", 2000));

    protected static final List<List<Employee>> listFlat = Arrays.asList(
            Arrays.asList(new Employee(1, "Alex", 1000),
                          new Employee(2, "Michael", 2000)),
            Arrays.asList(new Employee(3, "Jack", 1500),
                          new Employee(4, "Owen", 1500)),
            Arrays.asList(new Employee(5, "Denny", 2000)));
}
相關文章
相關標籤/搜索