目录
Stream流的中间方法
filter
案例:过滤出以张开头的元素
public class StreamDemo6 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","周芷若","赵敏","张强","张三丰","张翠山","王二狗","谢广坤");
list.stream().filter(s->s.startsWith("张")).forEach(s-> System.out.println(s));
}
}
打印结果:
limit
案例:获取前三个元素
public class StreamDemo7 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","周芷若","赵敏","张强","张三丰","张翠山","王二狗","谢广坤");
list.stream().limit(3).forEach(s-> System.out.println(s));
}
}
打印结果:
skip
案例:跳过前三个元素
public class StreamDemo8 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","周芷若","赵敏","张强","张三丰","张翠山","王二狗","谢广坤");
list.stream().skip(3).forEach(s-> System.out.println(s));
}
}
打印结果:
distinct
案例:去除重复的元素
public class StreamDemo9 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","张无忌","张无忌","周芷若","赵敏","张强","张三丰","张翠山","王二狗","谢广坤");
list.stream().distinct().forEach(s-> System.out.println(s));
}
}
打印结果:
concat
案例:合并list1和list2的流
public class StreamDemo10 {
public static void main(String[] args) {
ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();
Collections.addAll(list1,"张无忌","周芷若","赵敏","张强");
Collections.addAll(list2,"张三丰","张翠山","王二狗","谢广坤");
Stream.concat(list1.stream(),list2.stream()).forEach(s-> System.out.println(s));
}
}
打印结果:
map
案例:获取每个元素的年龄
public class StreamDemo11 {
public static void main(String[] args) {
ArrayList<String> list1 = new ArrayList<>();
Collections.addAll(list1,"张无忌-19","周芷若-20","赵敏-30","张强-40");
list1.stream()
.map(s->Integer.parseInt(s.split("-")[1]))
.forEach(s-> System.out.println(s));
}
}
打印结果: