创建流的几种方式
本文记录学习java8的一些总结。
以下主要介绍创建流的几种方式,直接上代码,仅供参考。
一、直接根据集合创建流
public static Stream<String> createStreamFromCollection(){
List<String> list = Arrays.asList("Hello", "world", "cgk", "work");
return list.stream();
}
二、根据Stream类的of()方法创建流
public static Stream<String> createStreamFromValues(){
return Stream.of("Hello", "world", "cgk", "work");
}
三、根据数组创建流
public static Stream<String> createStreamFromArrays(){
return Arrays.stream(new String[]{"Hello", "world", "cgk", "work"});
}
四、从文件中创建流
public static Stream<String> createStreamFromFile(){
Path path = Paths.get("E:\\code\\java\\java8\\src\\main\\java\\com\\cgk\\java8\\stream\\CreateStream.java");
try {
Stream<String> lines = Files.lines(path);
return lines;
} catch (IOException e) {
// e.printStackTrace();
throw new RuntimeException();
}
}
五、从迭代器中创建流
public static Stream<Integer> createStreamFromIterator(){
Stream<Integer> tStream = Stream.iterate(0, n -> n + 2).limit(10);
return tStream;
}
六、从生成器中创建流
public static Stream<Double> createStreamFromGenerator(){
return Stream.generate(Math::random).limit(5);
}
衍生出来的另一种:
public static Stream<String> createObjStreamFromGenerator(){
return Stream.generate(new ObjSupplier().get());
}
public class ObjSupplier implements Supplier<Obj>{
int index = 0;
Random random = new Random(System.currentTimeMillis());
@Override
public Obj get() {
index = random.nextInt(100);
return new Obj(index,"name->"+index);
}
}
static class Obj{
private Integer id;
private String name;
public Obj(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "obj{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
此外还有DoubleStream和IntegerStream也可以创建流。