JDK1.8 lambda常用方法

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 personArrayList = new ArrayList<>();
    personArrayList.add(person);

//根据条件获取指定字段的新集合
List a = personArrayList.stream().filter(Person -> Person.getName() == "Yellow").collect(Collectors.toList());

//遍历集合
personArrayList.forEach(e -> e.getName());

//排序(o1, o2升序,o2,o1降序)
List personList = personArrayList.stream().sorted((o1, o2) -> o1.getName().compareTo(o2.getName())).collect(Collectors.toList());
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 = personArrayList.stream().collect(Collectors.toMap(Person::getName, Function.identity()));

//遍历Map集合
map.forEach((k, v) -> {
System.out.println(k);
});

//使用Map.Entry遍历map
for (Map.Entry it : map.entrySet()) {
System.out.println(it.getKey() + "-" + it.getValue());
}

//使用迭代器遍历map
Iterator> iterator = map.entrySet().iterator();//返回所有的entry实体
while (iterator.hasNext()) {
Map.Entry next1 = iterator.next();
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> listMap = personArrayList.stream().collect(Collectors.groupingBy(Person::getName));

//合并分组之后的value
List personLists = listMap.values().stream().flatMap(Collection::stream).collect(Collectors.toList());

//判断集合是否存在某个值
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);

你可能感兴趣的:(JDK1.8 lambda常用方法)