java如何获取流stream呢?

java如何获取流stream呢?

转自:

http://www.java265.com/JavaJingYan/202207/16566384353851.html

下文笔者讲述使用Java代码生成stream流的方法分享,如下所示:

stream流简介

Java.util.stream.Stream是Java 8新加入的接口
目前它的使用率非常之高,那么如何获取及生成一个流呢?下文笔者将一一道来,如下所示:
 
-Collection集合都可使用stream默认方法获取流
default Stream stream()

-Stream接口的静态方法of可以获取数组对应的流
static Stream of(T···values)
参数是一个可变参数,那么我们就可以传递一个数组

public class DemoGetStream {
    public static void main(String[] args) {
        //把集合转换为Stream流
        List<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();

        Set<String> set = new HashSet<>();
        Stream<String> stream2 = set.stream();

        Map<String,String> map = new HashMap<>();
        //获取键,存储到一个Set集合中
        Set<String> keySet = map.keySet();
        Stream<String> stream3 = keySet.stream();

        //获取值,存储到一个Collection集合中
        Collection<String> values = map.values();
        Stream<String> stream4 = values.stream();

        //获取键值对(键与值的映射关系 entrySet)
        Set<Map.Entry<String, String>> entries = map.entrySet();
        Stream<Map.Entry<String, String>> stream5 = entries.stream();

        //把数组转换为Stream流
        Stream<Integer> stream6 = Stream.of(1, 2, 3, 4, 5);
        //可变参数可以传递数组
        Integer[] arr = {1,2,3,4,5};
        Stream<Integer> stream7 = Stream.of(arr);
        String[] arr2 = {"a","bb","ccc"};
        Stream<String> stream8 = Stream.of(arr2);
    }
}
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » java如何获取流stream呢?