Lambda用法

Lambda用法

  1. 占位符
package Test;


import com.alibaba.fastjson.JSON;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args) {


        Student Ming = new Student("小明", "男", "1");
        Student Red = new Student("小红", "女", "1");
        Student Gang = new Student("小刚", "男", "2");
        Student Bai = new Student("小白", "男", "2");
        Student Lan = new Student("小蓝", "男", "3");
        List<Student> list = new ArrayList<>();
        Collections.addAll(list, Ming, Red, Gang, Bai, Lan);
        System.out.println(JSON.toJSON(list) + "\n");
        // TODO 输出: [{"sex":"男","name":"小明","clazz":"1"},{"sex":"男","name":"小刚","clazz":"2"},{"sex":"女","name":"小红","clazz":"1"},{"sex":"男","name":"小白","clazz":"2"},{"sex":"男","name":"小蓝","clazz":"3"}]

        //根据性别分组
        list.stream().collect(Collectors.groupingBy(Student::getClazz)).forEach((k, v) -> System.out.println(JSON.toJSON(k + ": " + v)));
        // TODO 输出: 1: [Test.Student(Name=小明, Sex=男, Clazz=1), Test.Student(Name=小红, Sex=女, Clazz=1)]
        // TODO 输出: 2: [Test.Student(Name=小刚, Sex=男, Clazz=2), Test.Student(Name=小白, Sex=男, Clazz=2)]
        // TODO 输出: 3: [Test.Student(Name=小蓝, Sex=男, Clazz=3)]

        System.out.println();

        // 将2、3班的移除
        List<Student> collect = list.stream().filter(student -> !student.getClazz().equals("3")).collect(Collectors.toList());
        collect.removeIf(k -> k.getClazz().equals("2"));

        System.out.println(JSON.toJSON(collect) + "\n");
        // TODO 输出: [{"sex":"男","name":"小明","clazz":"1"},{"sex":"女","name":"小红","clazz":"1"}]

        // 装载Map集合,
        // TODO: map集合本身key不能重复,value是可以重复的    Java Duplicate key
        Map<String, String> storeMap = list.stream().collect(Collectors.toMap(student -> {return student.getName();}, Student::getClazz));
        storeMap.forEach((k,v) -> System.out.println("{key=" + k + ", value=" + v + "}"));
        // TODO 输出: {key=小刚, value=2} {key=小明, value=1} {key=小蓝, value=3} {key=小白, value=2} {key=小红, value=1}
    }

    @Data
    static class Student {
        private String Name;
        private String Sex;
        private String Clazz;

        Student(String name, String sex, String clazz) {
            Name = name;
            Sex = sex;
            Clazz = clazz;
        }
    }
}

上一篇:如何判断指定Class是否是基础数据类型或者是其包装类型


下一篇:Spring Framework自动装配setAutowireMode和Mybatis案例的源码探究