0
点赞
收藏
分享

微信扫一扫

Stream流-如何生成流

小编 2023-08-03 阅读 69

1. 通过集合

List<String> asList = Arrays.asList("11", "22", "33", "44", "55");
asList.stream()
            .forEach(System.out::println);
// 输出
//11
//22
//33
//44
//55

2. map生成流

Map<String,Integer> myMap=new HashMap<String,Integer>(){
    {
        put("一号人物",1);
        put("二号人物",2);
        put("三号人物",3);
        put("四号人物",4);
        put("五号人物",5);

    }
};

myMap.keySet().stream().forEach(s -> System.out.print(s+","));
System.out.println();
myMap.values().forEach(s-> System.out.print(s+","));
System.out.println();
myMap.entrySet().forEach(s-> System.out.print(s+","));
//输出
//二号人物,三号人物,四号人物,一号人物,五号人物,
//2,3,4,1,5,
//二号人物=2,三号人物=3,四号人物=4,一号人物=1,五号人物=5,

3. 数组生成流

Arrays.stream(new int[]{1,5,3,6,8,87})
        .forEach(System.out::println);
// 输出
//1
//5
///3
//6
//8
//87

4. 值生成流

// 通过Stream的of方法生成流,通过Stream的empty方法可以生成一个空流.
Stream.of(11,12,15,16,1856,1777,110)
    .forEach(System.out::println);
// 输出
//11
//12
//15
//16
//1856
//1777
//110

5. 通过文件生成

// 通过Files.line方法得到一个流,并且得到的每个流是给定文件中的一行.
try {
    Stream<String> lines = Files.lines(Paths.get("D:\\tmp\\test.txt"), Charset.defaultCharset());
    lines.forEach(System.out::println);
} catch (IOException e) {
    throw new RuntimeException(e);
}

6. 通过函数生成

// iterate方法接受两个参数,第一个为初始化值,第二个为进行的函数操作,因为iterator生成的流为无限流,通过limit方法对流进行了截断,只生成5个偶数。
Stream<String> iterateStream = Stream.iterate("test", t -> {
    int second = LocalDateTime.now().getSecond();
    return t + second;
}).limit(3);
iterateStream.forEach(System.out::println);
// 输出
//test
//test50
//test5050

Stream<String> limit = Stream.generate(() -> {
    Random random = new Random();
    String i = "test-"+random.nextInt(12);
    return i;
}).limit(3);

limit.forEach(System.out::println);
// 输出
//test-2
//test-1
//test-10

7. 生成并行流

List<Person> personList = createPersonList();
personList.stream().parallel().forEach(person -> System.out.println("person = " + person));
personList.parallelStream()
        .forEach(person -> System.out.println("person = " + person));

举报

相关推荐

Stream流

stream流

Stream流(Java)

Stream流编程

Stream流常用

Java | Stream流

Stream流分组

0 条评论