Lambda用法
- 占位符
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) + "
");
// 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) + "
");
// 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;
}
}
}
- 改变元素
public class T {
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Student student01 = new Student().setId(1).setName("张三").setDate(String.valueOf(new Date()));
Student student02 = new Student().setId(2).setName("历史").setDate(new Date().toString());
List<Student> list = Lists.newArrayList();
Collections.addAll(list, student01, student02);
// 关键代码
System.out.println("数量:" + list.stream().map(Student::getId).distinct().count());
System.out.println("转Map:" + list.stream().collect(Collectors.toMap(Student::getId, Student::getName)));
// 注:TODO: 实体类注解:@Accessors(chain = true)
System.out.println("改变原集合数据格式为:" + list.stream().map(item -> new Student().setId(item.getId() + 1).setName("SpringBoot").setDate(dateFormat.format(new Date()))).collect(Collectors.toList()));
}
}