JDK1.8 lambda常用方法
package com.company;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
- 描述:
- @author zwl
- @version 1.0
- @create 2020-11-10 11:28
*/
public class LambdaDemo {
public static void main(String[] args) {
Person person = new Person();
person.setAge(21);
person.setMessage("Hello World!");
person.setName("Green");
ListpersonArrayList = new ArrayList<>();
personArrayList.add(person);
//根据条件获取指定字段的新集合
List
//遍历集合
personArrayList.forEach(e -> e.getName());
//排序(o1, o2升序,o2,o1降序)
List
personArrayList.stream().sorted(Comparator.comparing(Person::getName));
//将集合某个字段组成新集合
personArrayList.stream().map(e -> e.getName()).collect(Collectors.toList());
//统计
personArrayList.stream().mapToInt(Person::getAge).sum();
//将指定字段存为Map
Map
//遍历Map集合
map.forEach((k, v) -> {
System.out.println(k);
});
//使用Map.Entry遍历map
for (Map.Entry
System.out.println(it.getKey() + "-" + it.getValue());
}
//使用迭代器遍历map
Iterator
while (iterator.hasNext()) {
Map.Entry
String key = next1.getKey();
Person person1 = next1.getValue();
System.out.println(key);
System.out.println(person1);
}
//实现Runnable接口
new Thread(() -> System.out.println("Hello World!")).start();
//分组
Map
//合并分组之后的value
List
//判断集合是否存在某个值
Boolean isPerson = personArrayList.stream().anyMatch(e -> "Green".equals(e.getName()));
//求集合某个字段最值
personArrayList.stream().mapToInt(Person::getAge).summaryStatistics().getMax();
//集合去重,去重后无序
personArrayList.stream().collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))));
personArrayList.stream().distinct().collect(Collectors.toList());
//limit限制返回个数
personArrayList.stream().limit(3).collect(Collectors.toList());
//skip删除元素
personArrayList.stream().skip(3).collect(Collectors.toList());
//reduce聚合
personArrayList.stream().map(e -> e.getAge()).reduce((sum, e) -> sum + e);