目录
Peek(用于在Stream流中获取元素同时执行一些操作,如打印、调试、观察等。通常会与其他的方法联合使用)
forEach(可将给定的方法应用于流中的每个元素。该方法是一种消费流的方式,不会返回值)
Filter(过滤)
案例:
public class StreamToOp {
public static void main(String[] args) {
List<String> list=new ArrayList<>();
list.add("java");
list.add("java2");
list.add("java3");
list.add("java4");
final List<String> list1 = list.stream().filter(item -> item.length() > 4).collect(Collectors.toList());
System.out.println(list1);
}
}
结果:
Map(转换)
public class StreamToOp {
public static void main(String[] args) {
List<student> list1=new ArrayList<>();
student student1=new student(1,"张三",18,"男");
student student2=new student(2,"张四",19,"男");
student student3=new student(2,"张五",20,"男");
list1.add(student1);
list1.add(student2);
list1.add(student3);
final Map<Integer, student> map = list1.stream().collect(Collectors.toMap(student::getId, Function.identity(), (key1, key2) -> key2));
System.out.println(map);
}
}
结果:
Function.identity()是获取对象本身
(key1, key2) -> key2 是如果key重复的话 用第二个key覆盖第一个
Sorted(排序)
public class StreamToOp {
public static void main(String[] args) {
int[] array= new int[]{1,5,2,3,8,4};
int[] array1 = Arrays.stream(array).sorted().toArray();
System.out.println(Arrays.toString(array1));
}
}
结果:
Distinct(去重)
public class StreamToOp {
public static void main(String[] args) {
int[] array= new int[]{1,5,2,3,8,4,4,1};
int[] array1 = Arrays.stream(array).distinct().toArray();
System.out.println(Arrays.toString(array1));
}
}
结果:
Limit(限制返回元素的个数)
public class StreamToOp {
public static void main(String[] args) {
int[] array = new int[]{1, 5, 2, 3, 8, 4, 4, 1};
int[] array1 = Arrays.stream(array).limit(5).toArray();
System.out.println(Arrays.toString(array1));
}
}
结果:
Skip(跳过前N个元素)
public class StreamToOp {
public static void main(String[] args) {
int[] array = new int[]{1, 5, 2, 3, 8, 4, 4, 1};
int[] array1 = Arrays.stream(array).skip(4).toArray();
System.out.println(Arrays.toString(array1));
}
}
结果:
Peek(用于在Stream流中获取元素同时执行一些操作,如打印、调试、观察等。通常会与其他的方法联合使用)
public class StreamToOp {
public static void main(String[] args) {
int[] array = new int[]{1, 5, 2, 3, 8, 4, 4, 1};
int[] array1 = Arrays.stream(array).peek(System.out::println).filter(item->item>3).toArray();
System.out.println(Arrays.toString(array1));
}
}
结果:
forEach(可将给定的方法应用于流中的每个元素。该方法是一种消费流的方式,不会返回值)
public class StreamToOp {
public static void main(String[] args) {
int[] array = new int[]{1, 5, 2, 3};
Arrays.stream(array).forEach(System.out::println);
}
}
结果: