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");
List<Person> personArrayList = new ArrayList<>();
personArrayList.add(person);
//根據(jù)條件獲取指定字段的新集合
List<Person> a = personArrayList.stream().filter(Person -> Person.getName() == "Yellow").collect(Collectors.toList());
//遍歷集合
personArrayList.forEach(e -> e.getName());
//排序(o1, o2升序,o2,o1降序)
List<Person> personList = personArrayList.stream().sorted((o1, o2) -> o1.getName().compareTo(o2.getName())).collect(Collectors.toList());
personArrayList.stream().sorted(Comparator.comparing(Person::getName));
//將集合某個(gè)字段組成新集合
personArrayList.stream().map(e -> e.getName()).collect(Collectors.toList());
//統(tǒng)計(jì)
personArrayList.stream().mapToInt(Person::getAge).sum();
//將指定字段存為Map
Map<String, Person> map = personArrayList.stream().collect(Collectors.toMap(Person::getName, Function.identity()));
//遍歷Map集合
map.forEach((k, v) -> {
System.out.println(k);
});
//使用Map.Entry遍歷map
for (Map.Entry<String, Person> it : map.entrySet()) {
System.out.println(it.getKey() + "-" + it.getValue());
}
//使用迭代器遍歷map
Iterator<Map.Entry<String, Person>> iterator = map.entrySet().iterator();//返回所有的entry實(shí)體
while (iterator.hasNext()) {
Map.Entry<String, Person> next1 = iterator.next();
String key = next1.getKey();
Person person1 = next1.getValue();
System.out.println(key);
System.out.println(person1);
}
//實(shí)現(xiàn)Runnable接口
new Thread(() -> System.out.println("Hello World!")).start();
//分組
Map<String, List<Person>> listMap = personArrayList.stream().collect(Collectors.groupingBy(Person::getName));
//合并分組之后的value
List<Person> personLists = listMap.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
//判斷集合是否存在某個(gè)值
Boolean isPerson = personArrayList.stream().anyMatch(e -> "Green".equals(e.getName()));
//求集合某個(gè)字段最值
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限制返回個(gè)數(shù)
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);