@Override
    public void visit(Shepherd s) {
      Stream.iterate(
          Color.RED, c -> Color.hsb(c.getHue() + .1, c.getSaturation(), c.getBrightness()));

      SpriteView tail =
          s.getAnimals().isEmpty() ? s : s.getAnimals().get(s.getAnimals().size() - 1);
      s.getAnimals()
          .addAll(
              Stream.iterate(tail, SpriteView.Lamb::new)
                  .substream(1, 8)
                  .collect(Collectors.toList()));
    }
 private static final List<List<Location>> gridWith(
     List<Location> topRow, Location topLeft, Location bottomLeft) {
   int rowCount = topLeft.equals(bottomLeft) ? 1 : topLeft.distanceFrom(bottomLeft) + 1;
   return Stream.iterate(topRow, row -> row.stream().map(Location::south).collect(toList()))
       .limit(rowCount)
       .collect(toList());
 }
  @Test
  public void testFirstLast() {
    Supplier<Stream<Integer>> s = () -> IntStreamEx.range(1000).boxed();
    checkShortCircuitCollector("first", Optional.of(0), 1, s, MoreCollectors.first());
    checkShortCircuitCollector(
        "firstLong",
        Optional.of(0),
        1,
        () -> Stream.of(1).flatMap(x -> IntStream.range(0, 1000000000).boxed()),
        MoreCollectors.first(),
        true);
    checkShortCircuitCollector(
        "first",
        Optional.of(1),
        1,
        () -> Stream.iterate(1, x -> x + 1),
        MoreCollectors.first(),
        true);
    assertEquals(
        1, (int) StreamEx.iterate(1, x -> x + 1).parallel().collect(MoreCollectors.first()).get());

    checkCollector("last", Optional.of(999), s, MoreCollectors.last());
    checkCollectorEmpty("first", Optional.empty(), MoreCollectors.first());
    checkCollectorEmpty("last", Optional.empty(), MoreCollectors.last());
  }
  @Test
  public void testHeadTail() {
    List<Integer> ints = IntStreamEx.range(1000).boxed().toList();
    checkShortCircuitCollector("tail(0)", Arrays.asList(), 0, ints::stream, MoreCollectors.tail(0));
    checkCollector("tail(1)", Arrays.asList(999), ints::stream, MoreCollectors.tail(1));
    checkCollector("tail(2)", Arrays.asList(998, 999), ints::stream, MoreCollectors.tail(2));
    checkCollector("tail(500)", ints.subList(500, 1000), ints::stream, MoreCollectors.tail(500));
    checkCollector("tail(999)", ints.subList(1, 1000), ints::stream, MoreCollectors.tail(999));
    checkCollector("tail(1000)", ints, ints::stream, MoreCollectors.tail(1000));
    checkCollector("tail(MAX)", ints, ints::stream, MoreCollectors.tail(Integer.MAX_VALUE));

    checkShortCircuitCollector("head(0)", Arrays.asList(), 0, ints::stream, MoreCollectors.head(0));
    checkShortCircuitCollector(
        "head(1)", Arrays.asList(0), 1, ints::stream, MoreCollectors.head(1));
    checkShortCircuitCollector(
        "head(2)", Arrays.asList(0, 1), 2, ints::stream, MoreCollectors.head(2));
    checkShortCircuitCollector(
        "head(500)", ints.subList(0, 500), 500, ints::stream, MoreCollectors.head(500));
    checkShortCircuitCollector(
        "head(999)", ints.subList(0, 999), 999, ints::stream, MoreCollectors.head(999));
    checkShortCircuitCollector("head(1000)", ints, 1000, ints::stream, MoreCollectors.head(1000));
    checkShortCircuitCollector(
        "head(MAX)", ints, 1000, ints::stream, MoreCollectors.head(Integer.MAX_VALUE));

    checkShortCircuitCollector(
        "head(10000)",
        IntStreamEx.rangeClosed(1, 10000).boxed().toList(),
        10000,
        () -> Stream.iterate(1, x -> x + 1),
        MoreCollectors.head(10000),
        true);
  }
Beispiel #5
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);
    }
  }
 @Test
 public void _02_무한_스트림_생성() {
   // 상수 무한 스트림
   Stream<String> echos = Stream.generate(() -> "Echo");
   // 난수 무한 스트림
   Stream<Double> randoms = Stream.generate(Math::random);
   // 무한 수열 스트림
   Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE));
 }
Beispiel #7
0
 @Test
 public void mustBeAbleToUseExpand() throws Exception {
   final JavaTestKit probe = new JavaTestKit(system);
   final List<String> input = Arrays.asList("A", "B", "C");
   CompletionStage<String> future =
       Source.from(input)
           .expand(in -> Stream.iterate(in, i -> i).iterator())
           .runWith(Sink.<String>head(), materializer);
   String result = future.toCompletableFuture().get(3, TimeUnit.SECONDS);
   assertEquals("A", result);
 }
Beispiel #8
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 #9
0
  private static void write(JsonGenerator g, List<List<Tokenizer.Token>> text) throws IOException {
    Stream<Pair<Tokenizer.Token, Integer>> s =
        StreamUtil.zip(text.stream(), Stream.iterate(0, i -> i + 1))
            .flatMap(p -> p.getA().stream().map(t -> Pair.of(t, p.getB())));

    g.writeStartArray();
    for (Pair<Tokenizer.Token, Integer> p : StreamUtil.asIterable(s)) {
      Tokenizer.Token t = p.getA();
      g.writeStartObject();
      g.writeStringField("pos", t.pos());
      g.writeStringField("text", tokenToString(t, p.getB()));
      g.writeEndObject();
    }
    g.writeEndArray();
  }
Beispiel #10
0
  /**
   * 指定された日と曜日の組み合わせのうち、最も今日に近い過去日を検索します。
   *
   * @param dayOfMonth 日
   * @param dayOfWeek 曜日
   * @return 検索された日
   */
  public static LocalDate lookForRecentDayOf(int dayOfMonth, DayOfWeek dayOfWeek) {

    LocalDate now = LocalDate.now();

    //		return Stream.iterate(now.withDayOfMonth(1), date -> date.minusMonths(1))    //
    // 本日の年月初日から、一月ずつ遡っていくストリームを生成する
    //			.filter(date -> checkLastDate(date, dayOfMonth))                         //
    // 末日が引数日より小さい月をフィルター
    //			.filter(date -> check(date, dayOfMonth, dayOfWeek))                      //
    // 該当日の曜日・過去日でないかをチェック
    //			.findFirst()                                                             // 最初の1件を探索し返却
    //			.get();

    return Stream.iterate(
            now.withDayOfMonth(1), date -> date.minusMonths(1)) // 本日の年月初日から、一月ずつ遡っていくストリームを生成する
        .filter(date -> date.lengthOfMonth() >= dayOfMonth) // 月末日が対象引数日以上の月を選択
        .map(date -> date.withDayOfMonth(dayOfMonth)) // 年月初日から引数日にマップ
        .filter(date -> date.getDayOfWeek().equals(dayOfWeek)) // 引数曜日と同じ日を選択
        .filter(date -> date.isBefore(now)) // 過去日を選択
        .findFirst() // 最初を選択し返却
        .get();
  }
 @Override
 public Publisher<Long> createPublisher(long elements) {
   return JDKReactiveStreamsPublisher.ofSync(Stream.iterate(0l, i -> i + 1l).limit(elements));
 }
Beispiel #12
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("");
  }
Beispiel #13
0
 public static Stream<BigInteger> stream() {
   return Stream.iterate(
           new BigInteger[] {BigInteger.ZERO, BigInteger.ONE},
           (BigInteger[] p) -> new BigInteger[] {p[1], p[0].add(p[1])})
       .map((BigInteger[] i) -> i[1]);
 }
 private static final Location getBottomLeft(Location northMost, Location southMost) {
   return Stream.iterate(northMost, Location::south)
       .filter(location -> !southMost.isSouthOf(location))
       .findFirst()
       .get();
 }
Beispiel #15
0
 private static Stream<Optional<PsiElement>> getSiblingsStream(PsiElement element) {
   return Stream.iterate(
       Optional.ofNullable(element),
       prev -> prev.map(e -> Optional.ofNullable(e.getNextSibling())).orElse(Optional.empty()));
 }
 private static final Location getTopRight(Location northMost, Location eastMost) {
   return Stream.iterate(northMost, Location::east)
       .filter(location -> !eastMost.isEastOf(location))
       .findFirst()
       .get();
 }
 private static final Location getTopLeft(Location northMost, Location westMost) {
   return Stream.iterate(northMost, Location::west)
       .filter(location -> !westMost.isWestOf(location))
       .findFirst()
       .get();
 }
 public static TemporalAdjuster next(Predicate<LocalDate> p) {
   return TemporalAdjusters.ofDateAdjuster(
       (d) -> Stream.iterate(nextDay(d), Ex3::nextDay).filter(p).findFirst().get());
 }
 public static long parallelSum(long n) {
   return Stream.iterate(1L, i -> i + 1).limit(n).parallel().reduce(Long::sum).get();
 }
 private static final List<Location> topRowWith(Location topLeft, Location topRight) {
   int columnCount = topLeft.equals(topRight) ? 1 : topLeft.distanceFrom(topRight) + 1;
   return Stream.iterate(topLeft, Location::east).limit(columnCount).collect(toList());
 }
 public static void main(String[] args) {
   List<String> list = new ArrayList<>();
   list.add("Abc");
   list.add("AXyz");
   java.util.stream.Stream.iterate(1, n -> n + 1).limit(10).forEach(System.out::println);
 }
 public static long sequentialSum(long n) {
   return Stream.iterate(1L, i -> i + 1).limit(n).reduce(Long::sum).get();
 }