Stream类常用操作
1.对比
public class StreamDemo01 { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("张无忌"); list.add("周芷若"); list.add("赵敏"); list.add("张强"); list.add("张三丰"); //遍历集合:使用面向对象的方式 //fori循环,迭代器,foreach循环 // for (String name : list) { // System.out.println(name); // } //体验一下Stream的优雅代码 list.stream().forEach(s-> System.out.println(s)); } }
2.获取流的方式
//a.集合获取流 ArrayList<String> arr1 = new ArrayList<String>(); Stream<String> s1 = arr1.stream(); HashSet<Integer> arr2 = new HashSet<Integer>(); Stream<Integer> s2 = arr2.stream(); //Map集合无法直接获取流 // 但是可以先获取键的集合再获取键流 HashMap<String,Integer> map = new HashMap<String, Integer>(); Stream<String> keyStream = map.keySet().stream(); //获取键流 Stream<Map.Entry<String,Integer>> entryStream = map.entrySet().stream(); //获取Entry流 //b.数组获取流 Stream<Integer> s3 = Stream.of(10,20,30,40);
3.
创建一个数组
Stream<String> s1 = Stream.of("jack","rose","marry","rom","jerry","hanny");
·逐个处理:forEach(代码演示)
//a.foreach 逐一处理 s1.forEach(new Consumer<String>() { @Override public void accept(String s) { System.out.println(s); } }); //Lambda替代上面的匿名内部类 s1.forEach((String s)->{System.out.println(s);}); //省略格式(推荐) s1.forEach(s->System.out.println(s));
·统计个数:count(代码演示)
//b.count 统计格式 long count = s1.count(); System.out.println("流中有:"+count+"个元素"); //Java中各种获取长度的方式 //数组.length; //字符串.length(); //集合.size() //流.count();
·过滤:filter(代码演示)
//c.filter 过滤 Stream<String> s2 = s1.filter(new Predicate<String>() { //用于过滤 public boolean test(String s) { //只要长度长4的字符串 return s.length() > 4; } }); //Lambda替代上面的匿名内部类 Stream<String> s2 = s1.filter((String s) -> {return s.length() > 4;}); //省略格式(推荐) Stream<String> s2 = s1.filter(s -> s.length() > 4);
·取前几个:limit(代码演示)
//d.limit 取前几个 Stream<String> s3 = s1.limit(4); s3.forEach(s-> System.out.println(s));
·跳过前几个:skip(代码演示)
//e.skip 跳过前几个 Stream<String> s4 = s1.skip(2); s4.forEach(s-> System.out.println(s));
·映射方法:map(代码演示)
//f.map 映射 Stream<Integer> s5 = s1.map(new Function<String, Integer>() { //映射方法 public Integer apply(String s) { return s.length(); } }); //Lambda替代上面的匿名内部类 Stream<Integer> s5 = s1.map((String s)->{return s.length();}); //省略格式 Stream<Integer> s5 = s1.map(s->s.length()); s5.forEach(s-> System.out.println(s));
·静态方法合并流:concat(代码演示)
//g.静态方法concat 用于合并两个流 Stream<Integer> one = Stream.of(1,2,3); Stream<Integer> two = Stream.of(4,5,6); Stream<Integer> all = Stream.concat(one,two); all.forEach(s-> System.out.println(s)); 注意: 1.如果是2个以上的流,那么2个2个慢慢合并 2.如果2个流泛型不一致,能合并吗?? 可以,合并后的流泛型是两个流泛型的共同父类
收集流
collect(Collectors.toList());
collect(Collectors.toSet());
toArray();