package cn.dj.demo.test;
import cn.dj.demo.domain.Student;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
public class TestStudent {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
studentList.add(new Student(1,"张三","23",new Date(),1));
studentList.add(new Student(1,"李四","24",new Date(),1));
studentList.add(new Student(1,"张瘦瘦","25",new Date(),1));
studentList.add(new Student(1,"李胖胖","26",new Date(),2));
studentList.add(new Student(1,"上课萨拉","33",new Date(),3));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 1.过滤年龄大于24的人 ,并且名字长度大于3的
List<Student> collect = studentList.stream().filter(s -> Integer.valueOf(s.getSAge()) > 24)
.filter(s -> s.getSName().length() > 3 )
.collect(Collectors.toList());
for (Student student : collect) {
System.out.println(student);
}
System.out.println("------------");
// 2. 获取学生名字和年龄的map ,并且是名字长度小于4的
Map<String, String> map = studentList.stream().filter(s -> s.getSName().length() < 4)
.collect(Collectors.toMap(Student::getSName, Student::getSAge));
Set<Map.Entry<String, String>> entries = map.entrySet();
entries.stream().forEach( i -> {
System.out.println(i.getKey() + "--" + i.getValue());
});
System.out.println("-----------");
List<String> nameList = studentList.stream().map(Student::getSName).collect(Collectors.toList());
for (String s : nameList) {
System.out.println(s);
}
System.out.println("-----------");
}
}
package cn.dj.demo.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer sId;
private String sName;
private String sAge;
private Date sBirthday;
private Integer sClass;
}
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
stream流过滤对象中的属性,将对象中某些字段转化为map
最新推荐文章于 2024-12-05 16:34:34 发布