default Stream<E> | stream() 返回以此集合作为源的顺序 |
Collection接口中的Stream方法可以将任何一个集合转换成一个流。
如果你有一个数组那么可以使用静态方法Stream.fo转换成一个流
map集合怎么获取流
public class Test2 {
public static void main(String[] args) {
HashMap<Integer, String> objectObjectHashMap = new HashMap<>();
objectObjectHashMap.put(1,"张三");
objectObjectHashMap.put(2,"李四");
objectObjectHashMap.put(3,"王五");
//根据map获取流
Stream<Map.Entry<Integer, String>> stream = objectObjectHashMap.entrySet().stream();
}
}
filter过滤器
public class Test {
public static void main(String[] args) {
ArrayList<String> strings = new ArrayList<>();
strings.add("张三");
strings.add("李四");
strings.add("王五");
strings.add("赵六");
strings.add("张七");
strings.add("王八");
//使用Stream流选出是张开头的,并且存储到集合中
List<String> zhang = strings.stream().filter(s -> s.startsWith("张")).collect(Collectors.toList());
//打印
zhang.forEach(System.out::println);
}
}
map相当于加工器,对流中的每一个元素进行修改加工
public class Test {
public static void main(String[] args) {
ArrayList<String> strings = new ArrayList<>();
strings.add("张三");
strings.add("李四");
strings.add("王五");
strings.add("赵六");
strings.add("张七");
strings.add("王八");
//使用Stream流选出是张开头的,并且存储到集合中
List<String> zhang = strings.stream().filter(s -> s.startsWith("张")).collect(Collectors.toList());
//打印
zhang.forEach(System.out::println);
//把上面筛选出来的数据进行加工
List<String> student = zhang.stream().map(s -> s.concat("同学")).collect(Collectors.toList());
student.forEach(System.out::println);
}
}
skip跳过前几个元素
limit返回几个元素
Stream流的终结方法:
count统计流中元素的个数
forEach逐一处理
collect收集,收集到单例集合Collectors.toList()、Collectors.toSet(),收集到数组当中Collectors.toArray()。