Java基础_Stream流
- Stream流的简单使用
- Stream流的获取
- Stream流的中间方法
- Stream流的终结方法
- 综合练习
- 数字过滤
- 字符串过滤并收集
- 自定义对象过滤并收集
- 来源
- Gitee地址
Stream流的简单使用
public class StreamDemo01 {public static void main(String[] args) {/*** 创建集合添加元素,完成以下需求:* 1.把所有以“张”开头的元素存储到新集合中* 2.把“张”开头的,长度为3的元素再存储到新集合中* 3.遍历打印最终结果*/ArrayList<String> list = new ArrayList<>();list.add("张无忌");list.add("周芷若");list.add("赵敏");list.add("张强");list.add("张三丰");list.stream().filter(name -> name.startsWith("张")).filter(name -> name.length() == 3).forEach(name -> System.out.println(name));// ArrayList<String> list1 = new ArrayList<>();// for (String name : list) {// if(name.startsWith("张")){// list1.add(name);// }// }//// ArrayList<String> list2 = new ArrayList<>();// for (String name : list1) {// if(name.length() == 3){// list2.add(name);// }// }//// for (String name : list2) {// System.out.println(name);// }}
}
Stream流的获取
- 单列集合
public class StreamDemo2 {public static void main(String[] args) {/*** 单列集合获取Stream流*/ArrayList<String> list = new ArrayList<>();Collections.addAll(list, "a", "b", "c", "d", "e");// list.stream().forEach(new Consumer<String>() {// @Override// public void accept(String s) {// System.out.println(s);// }// });list.stream().forEach(s -> System.out.println(s));} }
- 双列集合
public class StreamDemo3 {public static void main(String[] args) {/*** 双列集合获取Stream流*/HashMap<String, Integer> map = new HashMap<String, Integer>();map.put("aaa", 111);map.put("bbb", 222);map.put("ccc", 333);map.put("ddd", 444);map.keySet().stream().forEach(key -> System.out.println(key));map.entrySet().stream().forEach(entry -> System.out.println(entry));} }
- 数组
public class StreamDemo4 {public static void main(String[] args) {/*** 数组获取Stream流*/int[] arr1 = {1, 2, 3, 4};String[] arr2 = {"a", "b", "c", "d"};Arrays.stream(arr1).forEach(num -> System.out.println(num));Arrays.stream(arr2).forEach(str -> System.out.println(str));/*** 注意:* Stream接口中静态方法of的细节* 方法的形参是一个可变参数,可以传递一堆零散的数据,也可以传递数组* 但是数组必须是引用数据类型的,如果传递基本数据类型,是会把整个数组当作一个元素,放到Stream中*/Stream.of(arr1).forEach(num -> System.out.println(num));//[I@448139f0Stream.of(arr2).forEach(str -> System.out.println(str));} }
- 零散数据
public class StreamDemo5 {public static void main(String[] args) {/*** 零散数据获取Stream流*/Stream.of(1, 2, 3, 4).forEach(num -> System.out.println(num));} }
Stream流的中间方法
- 注意
- 中间方法,返回新的Stream流,原来的Stream流只能用一次,建议使用链式编程
- 修改Stream流中的数据,不会影响原来集合或者数组中的数据
- filter,skip,limit
public class StreamDemo6 {public static void main(String[] args) {/*** Stream流的中间方法* filter, skip, limit*/ArrayList<String> list = new ArrayList<>();Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张强", "张三丰");// list.stream().filter(new Predicate<String>() {// @Override// public boolean test(String s) {// return s.startsWith("张");// }// }).forEach(s -> System.out.println(s));// filter 过滤System.out.println("filter");list.stream().filter(s -> s.startsWith("张")).forEach(s -> System.out.println(s));// limit 获取前几个元素System.out.println("limit");list.stream().limit(3).forEach(str -> System.out.println(str));// skip 跳过前几个元素System.out.println("skip");list.stream().skip(3).forEach(str -> System.out.println(str));// 练习:获取[2, 3]System.out.println("[2, 3]的元素为");list.stream().skip(2).limit(2).forEach(s -> System.out.println(s));} }
- distinct,concat
public class StreamDemo7 {public static void main(String[] args) {/*** distinct, concat*/ArrayList<String> list1 = new ArrayList<>();Collections.addAll(list1, "张无忌", "张无忌", "张无忌", "周芷若", "赵敏", "张强", "张三丰");ArrayList<String> list2 = new ArrayList<>();Collections.addAll(list2, "Tommy", "Jelly", "Mike");// distinct 元素去重,依赖hashCode和equals方法(底层是HashSet)list1.stream().distinct().forEach(s -> System.out.println(s));// concat 合并a和b为一个流System.out.println("concat");Stream.concat(list1.stream(), list2.stream()).forEach(s -> System.out.println(s));} }
- map
public class StreamDemo8 {public static void main(String[] args) {/*** map*/// map 转换流中的数据类型ArrayList<String> list = new ArrayList<>();Collections.addAll(list, "张无忌-18", "周芷若-19", "赵敏-21", "张强-23", "张三丰-27");/*** 第一个类型:流中原本的数据类型* 第二个类型:转换后的类型* apply的形参s:依次表视流里面的每一个数据* 返回值:表视转换之后的数据** map方法执行完毕之后,流上的数据就变成了整数*/// list.stream().map(new Function<String, Integer>() {// @Override// public Integer apply(String s) {// String[] split = s.split("-");// int age = Integer.parseInt(split[1]);// return age;// }// }).forEach(num -> System.out.println(num));list.stream().map(s -> {String[] split = s.split("-");int age = Integer.parseInt(split[1]);return age;}).forEach(num -> System.out.println(num));} }
Stream流的终结方法
- forEach, count, toArray
public class StreamDemo9 {public static void main(String[] args) {/*** forEach, count, toArray*/ArrayList<String> list = new ArrayList<>();Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张强", "张三丰", "张翠山", "张良", "王二麻子", "谢广坤");System.out.println("forEach");// void forEach(Consumer action) 遍历// Consumer的泛型:表示流中数据的类型// accept方法的形参s:依次表视流里面的每一个数据// 方法体:对每一个数据的处理操作// list.stream().forEach(new Consumer<String>() {// @Override// public void accept(String s) {// System.out.println(s);// }// });list.stream().forEach(s -> System.out.println(s));System.out.println("count");// long count 统计System.out.println(list.stream().count());System.out.println("toArray");// toArray 收集流中的数据,放到数组中/* 1Object[] objects = list.stream().toArray();System.out.println(Arrays.toString(objects));*//* 2String[] arr1 = list.stream().toArray(new IntFunction<String[]>() {@Overridepublic String[] apply(int value) {return new String[value];}});System.out.println(Arrays.toString(arr1));*/String[] arr2 = list.stream().toArray(value -> new String[value]);System.out.println(Arrays.toString(arr2));} }
- collect
public class StreamDemo10 {public static void main(String[] args) {/*** collect*/ArrayList<String> list = new ArrayList<>();Collections.addAll(list, "张无忌-男-13", "张无忌-男-13", "周芷若-女-17", "赵敏-女-21", "张强-男-23", "张三丰-男-27", "张翠流-女-31", "张良-男-34", "王二麻子-男-37", "谢广坤-男-41");// collect(Collector collector) 收集流中的数据,放到集合中(List Set Map)// 收集男性System.out.println("toList");List<String> list1 = list.stream().filter(s -> "男".equals(s.split("-")[1])).collect(Collectors.toList());System.out.println(list1);System.out.println("toSet");Set<String> set = list.stream().filter(s -> "男".equals(s.split("-")[1])).collect(Collectors.toSet());System.out.println(set);System.out.println("toMap");// Map<String, Integer> map = set.stream()// .filter(s -> "男".equals(s.split("-")[1]))// .collect(Collectors.toMap(// new Function<String, String>() {// @Override// public String apply(String s) {// return s.split("-")[0];// }// },// new Function<String, Integer>() {// @Override// public Integer apply(String s) {// return Integer.parseInt(s.split("-")[2]);// }// }// ));Map<String, Integer> map = set.stream().collect(Collectors.toMap(s -> s.split("-")[0],s -> Integer.parseInt(s.split("-")[2])));System.out.println(map);} }
综合练习
数字过滤
public class StreamDemo11 {public static void main(String[] args) {/*** 定义一个集合,并添加一些整数1,2,3,4,5,6,7,8,9,10* 过滤奇数,只留下偶数。* 并将结果保存起来*/ArrayList<Integer> list = new ArrayList<>();Collections.addAll(list, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);List<Integer> res = list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());System.out.println(res);}
}
字符串过滤并收集
public class StreamDemo12 {public static void main(String[] args) {/*** 创建一个ArrayList集合,并添加以下字符串,字符串中前面是姓名,后面是年龄* “zhangsan,23"* “lisi,24”* "wangwu,25”* 保留年龄大于等于24岁的人,并将结果收集到Map集合中,姓名为键,年龄为值*/ArrayList<String> list = new ArrayList<>();Collections.addAll(list, "zhangsan,23", "lisi,24", "wangwu,25");Map<String, Integer> map = list.stream().filter(s -> Integer.parseInt(s.split(",")[1]) >= 24).collect(Collectors.toMap(s -> s.split(",")[0],s -> Integer.parseInt(s.split(",")[1])));System.out.println(map);}
}
自定义对象过滤并收集
public class StreamDemo13 {public static void main(String[] args) {/*** 现在有两个ArrayList集合* 第一个集合中:存储6名男演员的名字和年龄。* 第二个集合中:存储6名女演员的名字和年龄* 姓名和年龄中间用逗号隔开。比如:张三,23* 要求完成如下的操作:* 1,男演员只要名字为3个字的前两人* 2,女演员只要姓杨的,并且不要第一个* 3,把过滤后的男演员姓名和女演员姓名合并到一起* 4,将上一步的演员信息封装成Actor对象:* 5,将所有的演员对象都保存到List集合中。* 备注:演员类Actor,属性有:name,age* "蔡坤坤,24","叶齁咸,23","刘不甜,22","吴签,24","谷嘉,30","肖梁梁,27"* "赵小颖,35”,"杨颖,36","高元元,43","张天天,31","刘诗,35","杨小幂,33"*/ArrayList<String> list1 = new ArrayList<>();Collections.addAll(list1, "蔡坤坤,24", "叶齁咸,23", "刘不甜,22", "吴签,24", "谷嘉,30", "肖梁梁,27");ArrayList<String> list2 = new ArrayList<>();Collections.addAll(list2, "赵小颖,35", "杨颖,36", "高元元,43", "张天天,31", "刘诗,35", "杨小幂,33");Stream<String> stream1 = list1.stream().filter(s -> s.split(",")[0].length() == 3).limit(2);Stream<String> stream2 = list2.stream().filter(s -> s.split(",")[0].startsWith("杨")).skip(1);Stream<String> stream3 = Stream.concat(stream1, stream2);List<Actor> list = stream3.map(s -> {String[] arr = s.split(",");String name = arr[0];int age = Integer.parseInt(arr[1]);return new Actor(name, age);}).collect(Collectors.toList());System.out.println(list);}
}
来源
黑马程序员. 阿玮Java零基础
Gitee地址
https://gitee.com/yu-ba-ba-ba/awJava