Beispiel #1
0
  public static void main(String[] args) throws IOException {
    Path path = Paths.get("../alice.txt");
    String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);

    Stream<String> words = Stream.of(contents.split("[\\P{L}]+"));
    show("words", words);
    Stream<String> song = Stream.of("gently", "down", "the", "stream");
    show("song", song);
    Stream<String> silence = Stream.empty();
    silence = Stream.<String>empty(); // Explicit type specification
    show("silence", silence);

    Stream<String> echos = Stream.generate(() -> "Echo");
    show("echos", echos);

    Stream<Double> randoms = Stream.generate(Math::random);
    show("randoms", randoms);

    Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));
    show("integers", integers);

    Stream<String> wordsAnotherWay = Pattern.compile("[\\P{L}]+").splitAsStream(contents);
    show("wordsAnotherWay", wordsAnotherWay);

    try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
      show("lines", lines);
    }
  }
Beispiel #2
0
  public static void main(String[] args) {

    out.println("Gauss: " + MAX * (MAX + 1) / 2); // 500000500000

    long sum = 0L;
    for (long i = 0; i <= MAX; i++) {
      sum = sum + i;
    }
    out.println("For loop: " + sum);

    Long another =
        Stream.iterate(0L, l -> ++l).limit(MAX + 1).collect(Collectors.summingLong(l -> l));

    out.println("With a Stream of Long and Collectors.summingLong: " + another);
  }
Beispiel #3
0
  public static void main(String[] args) {

    /*one way*/
    Stream.iterate(0, n -> n + 1).map(n -> n + " ").limit(10).parallel().forEach(out::print);
    out.println("");
  }
 public static long parallelSum(long n) {
   return Stream.iterate(1L, i -> i + 1).limit(n).parallel().reduce(Long::sum).get();
 }
 public static long sequentialSum(long n) {
   return Stream.iterate(1L, i -> i + 1).limit(n).reduce(Long::sum).get();
 }