public class StreamDemo {
static class Student{
private int age;
public Student(int age){
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static void main(String[] args) {
List<Long> streamList = Arrays.asList(2L,3L,4L,5L,6L,2L,3L,4L);
//遍历
List<Long> longList = streamList.stream().collect(Collectors.toList());
//longList.forEach(System.out::print);
//筛选
List<Long> longList1 = streamList.stream().filter(o -> o>3).collect(Collectors.toList());
// longList1.forEach(System.out::print);
//去重
List<Long> longList2 = longList1.stream().distinct().collect(Collectors.toList());
//longList2.forEach(System.out::print);
//排序
List<Long> longList3 = streamList.stream().sorted().collect(Collectors.toList());
//longList3.forEach(System.out::print);
//统计
long count = streamList.stream().count();
//System.out.println(count);
Student s1 = new Student(20);
Student s2 = new Student(10);
List<Student> studentList = Arrays.asList(s1,s2);
//组装一
List<Integer> ageList = studentList.stream().map(Student::getAge).collect(Collectors.toList());
// ageList.forEach(System.out::print);
//组装二
List<String> stringList = Arrays.asList("1,2,3,4","2,3,4,5");
List<String> longList4 = stringList.stream().map(o -> o.replaceAll(",",""))
.collect(Collectors.toList());
longList4.forEach(System.out::print);
}
}
Java8 stream()常用方法
最新推荐文章于 2022-04-07 11:38:00 发布