数组:
package com.Lucky; import java.util.*; /* 数组的Stream流: 使用Arrays工具类 */ public class StreamArray { public static void main(String[] args) { //创建数组 int[] array={1,2,3,4,5,6,7,8,9}; Arrays.stream(array).forEach(s-> System.out.print(s+"\t")); } }
单列集合:
package com.Lucky; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; /* 单列集合的Stream流: 可以直接使用 */ public class StreamList { public static void main(String[] args) { //创建单列集合 ArrayList<String> strList=new ArrayList<>(); LinkedList<String> LinkedList=new LinkedList<>(); Collections.addAll(strList,"BUG","人才","精英","天才"); Collections.addAll(LinkedList,"人才","精英","天才"); //采用Stream流 strList.stream().forEach(s-> System.out.print(s)); System.out.println(); LinkedList.stream().forEach(s-> System.out.print(s)); } }
双列集合:
package com.Lucky; import java.util.*; /* 双列集合的Stream流: 需要将双列集合数据转化成单列集合才能使用Stream */ public class StreamMap { public static void main(String[] args) { //创建双列集合 HashMap<String,Integer> strMap=new HashMap<>(); LinkedHashMap<String,Integer> linkedMap=new LinkedHashMap<>(); TreeMap<String,Integer> treeMap=new TreeMap<>(); strMap.put("BUG",999); strMap.put("Stream",666); strMap.put("唯易",5555); linkedMap.putAll(strMap); treeMap.put("TreeMap",666); treeMap.put("TreeMapBug",999); //采用Stream流 //①将双列集合转换成单列集合【采用keySet】 System.out.println("---- //①将双列集合转换成单列集合【采用keySet】-----"); Set<String> str = strMap.keySet(); Set<String> strLink = linkedMap.keySet(); Set<String> strTree = treeMap.keySet(); str.stream().forEach(s-> System.out.println(s)); strLink.stream().forEach(s-> System.out.println(s)); strTree.stream().forEach(s-> System.out.println(s)); // ②将双列集合转换成单列集合【采用entrySey】 System.out.println("---- // ②将双列集合转换成单列集合【采用entrySey】-----"); Set<Map.Entry<String, Integer>> ent = strMap.entrySet(); Set<Map.Entry<String, Integer>> entLink = strMap.entrySet(); Set<Map.Entry<String, Integer>> entTree = strMap.entrySet(); ent.stream().forEach(s-> System.out.println(s)); entLink.stream().forEach(s-> System.out.println(s)); entTree.stream().forEach(s-> System.out.println(s)); } }
其他:
package com.Lucky; import java.util.Arrays; import java.util.stream.Stream; /* 其他的Stream流: 直接Stream.of 小细节:在Stream接口的of方法中,形参是一个可变参数,可以传递一些零散的数据,也可以是数组 **但是数组的类型必须是引用类型的,不然就会将整个数组当成一个元素,存储在Stream中 */ public class StreamOther { public static void main(String[] args) { Stream.of(1,2,3,4,5).forEach(s-> System.out.print(s+"\t")); System.out.println(); Stream.of("K","N","C","X","Z").forEach(s-> System.out.print(s+"\t")); System.out.println(); Stream.of('c','x','b','g','k').forEach(s-> System.out.print(s+"\t")); System.out.println(); System.out.println("-------- 小细节实战----------"); //但是数组的类型必须是引用类型的,不然就会将整个数组当成一个元素,存储在Stream中 int[] arr={1,2,3,4,5,6}; //int类型的数组 Stream.of(arr).forEach(s-> System.out.println(s)); } }
标签:stream,Stream,流之,System,forEach,使用,println,out From: https://www.cnblogs.com/Lucky-only/p/16970938.html