Java λ表达式
λ表达式本质上是一个匿名方法。
记录常用方法(简单)
stream
@Test
public void test2() {
List<Integer> nums = Lists.newArrayList(1, 1, null, 2, 3, 4, null, 5, 6, 7, 8, 9, 10);
System.out.println("sum is:" + nums.stream().
filter(num -> num != null).//过滤
distinct().//去重
mapToInt(num -> num * 2).//map处理
peek(System.out::println).//处理流,不改变原来流
skip(2).
limit(4).
sum()
);
}
运行结果
2
4
6
8
10
12
sum is:36
再来个例子
Employee实体类
public class Employee {
private String name;
private int age;
private String gender;
private double salary;
//get and set
//toString
//contructor
}
public class Notes {
private List<Employee> employeeList=Lists.newArrayList();
@Before
public void setUp(){
employeeList.add(new Employee("James",16,"M",10000));
employeeList.add(new Employee("Kobe",17,"M",200000));
employeeList.add(new Employee("AB",19,"F",2000));
employeeList.add(new Employee("ABC",18,"F",20000));
employeeList.add(new Employee("ABCD",20,"F",20000));
employeeList.add(new Employee("ABCDE",21,"M",20000));
employeeList.add(new Employee("ABCD",15,"M",20000));
employeeList.add(new Employee("ABCD",15,"M",20000));
employeeList.add(new Employee("ABCD",15,"M",20000));
}
//排序
@Test
public void testSort(){
employeeList.stream().sorted((a,b) ->(a.getName().length()-b.getName().length())).forEach(System.out::println);
}
@Test
public void testGroupingBy(){
Map<String,List<Employee>> employeeMap= employeeList.stream().distinct().
collect(Collectors.groupingBy(p ->p.getGender()));
System.out.println(employeeMap.get("M"));
System.out.println(employeeMap.get("F"));
}
@Test/
public void testPartitioningBy(){
Map<Boolean,List<Employee>> employeeMap= employeeList.stream().
collect(Collectors.partitioningBy(p -> p.getAge()>=18));
System.out.println(employeeMap.get(true));
System.out.println(employeeMap.get(false));
}
//list 转 Map 保证key不重复
Map<String, String> areaMap = areaList.stream().collect(Collectors.toMap(Area::getAreaCode, Area::getAreaName));
//list去重
@Test public void test3() { List<TcPlace> tcPlaces = new ArrayList<>(); tcPlaces.add(new TcPlace(13L, "大毛")); tcPlaces.add(new TcPlace(14L, "二毛")); tcPlaces.add(new TcPlace(15L, "三毛")); tcPlaces.add(new TcPlace(13L, "四毛")); List<TcPlace> tcPlaces22 = tcPlaces.stream().collect( Collectors.collectingAndThen(Collectors.toCollection( () -> new TreeSet<>(Comparator.comparing(o -> o.getId()))), ArrayList::new) ); }