赞
踩
代码示例
@Test
public void test1(){
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> stream = list.stream();
System.out.println(stream);
}
代码示例
@Test
public void test2(){
String [] arr = {"aaa","bbb","ccc"};
Stream<String> stream = Arrays.stream(arr);
System.out.println(stream);
}
代码示例
@Test
public void test3(){
Stream<Integer> stream = Stream.of(1, 2, 3);
System.out.println(stream);
}
代码示例,测试所用的集合
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {
private Long id;
private String name;
private Integer age;
}
public class StudentUtil {
private static List<Student> studentList;
static {
studentList = new ArrayList<Student>();
Student student1 = new Student(1L,"www",19);
Student student2 = new Student(2L,"ddd",18);
Student student3 = new Student(3L,"lll",20);
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
}
public static List<Student> getStudentList(){
return studentList;
}
}
代码示例
@Test
public void test4(){
List<Student> studentList = StudentUtil.getStudentList();
studentList.stream().filter(student -> student.getAge() > 18).forEach(System.out::println);
}
执行结果
Student(id=1, name=www, age=19)
Student(id=3, name=lll, age=20)
代码示例
@Test
public void test5(){
List<Student> studentList = StudentUtil.getStudentList();
studentList.stream().distinct().forEach(System.out::println);
}
运行结果
Student(id=1, name=www, age=19)
Student(id=2, name=ddd, age=18)
Student(id=3, name=lll, age=20)
@Test
public void test6(){
List<Student> studentList = StudentUtil.getStudentList();
studentList.stream().limit(2).forEach(System.out::println);
}
运行结果
Student(id=1, name=www, age=19)
Student(id=2, name=ddd, age=18)
@Test
public void test7(){
List<Student> studentList = StudentUtil.getStudentList();
studentList.stream().skip(1).forEach(System.out::println);
}
运行结果
Student(id=2, name=ddd, age=18)
Student(id=3, name=lll, age=20)
代码示例
@Test
public void test8(){
List<Student> studentList = StudentUtil.getStudentList();
studentList.stream().map(student -> student.getName()).forEach(System.out::println);
}
运行结果
www
ddd
lll
代码示例
@Test
public void test8(){
List<Student> studentList = StudentUtil.getStudentList();
studentList.stream().map(student -> student.getName()).forEach(System.out::println);
}
运行结果
w
d
l
sorted(Compartor c)
代码示例
@Test
public void test10(){
List<Student> studentList = StudentUtil.getStudentList();
studentList.stream().sorted((s1,s2)->s1.getAge()-s2.getAge()).forEach(System.out::println);
}
运行结果
Student(id=2, name=ddd, age=18)
Student(id=1, name=www, age=19)
Student(id=3, name=lll, age=20)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。