@Test
  public void test() throws InterruptedException {
    ObstructionFreeStm stm = new ObstructionFreeStm();
    List<Memory<Integer>> memories =
        IntStream.range(0, nMemories) //
            .mapToObj(i -> stm.create(0))
            .collect(Collectors.toList());
    List<Worker> workers =
        IntStream.range(0, nTransactions) //
            .mapToObj(i -> new Worker(stm))
            .collect(Collectors.toList());

    List<Integer> workingOrders = new ArrayList<>();
    IntStream.range(0, nMemories * 2 + 1)
        .forEach(mi -> IntStream.range(0, nTransactions).forEach(workingOrders::add));
    Collections.shuffle(workingOrders, random);

    for (int workingOrder : workingOrders) workers.get(workingOrder).work(memories);

    stm.transaction(
        transaction -> {
          int sum = 0;

          for (Memory<Integer> memory : memories) {
            int read = stm.get(transaction, memory);
            System.out.println("FINAL MEMORY VALUE = " + read);
            sum += read;
          }

          if (sum != 0) throw new RuntimeException("Final sum is not zero, but is " + sum);

          return true;
        });
  }
 // http://www.had2know.com/academics/integer-triangles-120-degree-angle.html
 public static int getTriangles(int perimeter) {
   return (int)
       IntStream.range(2, perimeter / 5)
           .mapToLong(
               m -> IntStream.range(1, m).filter(n -> checkPerimeter(m, n, perimeter)).count())
           .sum();
 }
Example #3
0
  @Test
  public void reduce() {
    IntStream stream = IntStream.of(1, 2, 3, 4);

    assertEquals(10, stream.reduce(0, (a, b) -> a + b));

    Stream<Integer> stream2 = Arrays.asList(1, 2, 3, 4).stream();

    stream2.reduce(0, (a, b) -> a + b);

    // obviously the operations can be more complex :)

    Stream<Integer> stream3 = Arrays.asList(1, 2, 3, 4).stream();

    // reduce is a superset of map :D
    System.err.println(
        stream3.reduce(
            new ArrayList<Integer>(),
            (List<Integer> a, Integer b) -> {
              a.add(b);
              return a;
            },
            (a, b) -> {
              List<Integer> c = new ArrayList<>(a);
              c.addAll(b);
              return c;
            }));
  }
Example #4
0
 public static void usingRanges() {
   System.out.println("Range 0 10");
   IntStream.range(0, 10).forEach(System.out::print);
   System.out.println("\nRange Closed 0 10");
   IntStream.rangeClosed(0, 10).forEach(System.out::print);
   int[] values = IntStream.rangeClosed(1, 100).toArray();
 }
  private void preselectDropDowns() {
    // idea: generally one type of document (i.e. from the same bank) will
    // be imported into the same account

    List<Account> activeAccounts = client.getActiveAccounts();
    if (!activeAccounts.isEmpty()) {
      String uuid =
          preferences.getString(IMPORT_TARGET_ACCOUNT + extractor.getClass().getSimpleName());

      // do not trigger selection listener (-> do not user #setSelection)
      primaryAccount
          .getCombo()
          .select(
              IntStream.range(0, activeAccounts.size())
                  .filter(i -> activeAccounts.get(i).getUUID().equals(uuid))
                  .findAny()
                  .orElse(0));
      secondaryAccount.getCombo().select(0);
    }

    List<Portfolio> activePortfolios = client.getActivePortfolios();
    if (!activePortfolios.isEmpty()) {
      String uuid =
          preferences.getString(IMPORT_TARGET_PORTFOLIO + extractor.getClass().getSimpleName());
      // do not trigger selection listener (-> do not user #setSelection)
      primaryPortfolio
          .getCombo()
          .select(
              IntStream.range(0, activePortfolios.size())
                  .filter(i -> activePortfolios.get(i).getUUID().equals(uuid))
                  .findAny()
                  .orElse(0));
      secondaryPortfolio.getCombo().select(0);
    }
  }
  public void example() {
    System.out.println(
        Stream.of(IntStream.of(1), IntStream.of(2)).flatMapToInt((IntStream s) -> s).sum());

    // unchanged, it's not using the varargs overload
    System.out.println(Stream.of(IntStream.of(1)).flatMap(s -> s.boxed()).mapToInt(i -> i).sum());
  }
    private Worker(ObstructionFreeStm stm) {
      this.stm = stm;
      this.transaction = stm.begin();

      IntStream.range(0, nMemories * 2).forEach(i -> orders.add(i % nMemories));
      Collections.shuffle(orders, random);

      Set<Integer> isRead = new HashSet<>();

      IntStream.range(0, nMemories * 2)
          .forEach(
              i -> {
                Integer mi = orders.get(i);
                orders.set(i, isRead.add(mi) ? mi : mi + nMemories);
              });

      orders.add(nMemories * 2);

      int sum = 0;

      for (int i = 1; i < nMemories; i++) {
        int adjustment = random.nextInt(100) - 50;
        adjustments.add(adjustment);
        sum += adjustment;
      }

      adjustments.add(-sum);
    }
 public static IntSummaryStatistics test() {
   return IntStream.range(0, 100)
           .flatMap(x -> IntStream.range(0, x).limit(x / 2))
           .limit(50)
           .summaryStat
       < caret
       > istics();
 }
 private List<Integer> range(int from, int to) {
   IntStream stream = IntStream.rangeClosed(from, to);
   List<Integer> result = new ArrayList<Integer>();
   for (int year : stream.toArray()) {
     result.add(year);
   }
   return result;
 }
Example #10
0
  /**
   * Tests the performance of an event listener on the map for Update events of 2 MB strings. Expect
   * it to handle at least 50 2 MB updates per second.
   */
  @Test
  public void testSubscriptionMapEventListenerUpdatePerformance() {
    _testMap.clear();

    // Put values before testing as we want to ignore the insert events
    Function<Integer, Object> putFunction =
        a -> _testMap.put(TestUtils.getKey(_mapName, a), _twoMbTestString);

    IntStream.range(0, _noOfPuts)
        .forEach(
            i -> {
              putFunction.apply(i);
            });

    Jvm.pause(100);
    // Create subscriber and register
    TestChronicleMapEventListener mapEventListener =
        new TestChronicleMapEventListener(_mapName, _twoMbTestStringLength);

    Subscriber<MapEvent> mapEventSubscriber = e -> e.apply(mapEventListener);
    clientAssetTree.registerSubscriber(
        _mapName + "?bootstrap=false", MapEvent.class, mapEventSubscriber);

    KVSSubscription subscription =
        (KVSSubscription) serverAssetTree.getAsset(_mapName).subscription(false);

    waitFor(() -> subscription.entrySubscriberCount() == 1);
    Assert.assertEquals(1, subscription.entrySubscriberCount());

    // Perform test a number of times to allow the JVM to warm up, but verify runtime against
    // average
    TestUtils.runMultipleTimesAndVerifyAvgRuntime(
        i -> {
          if (i > 0) {
            waitFor(() -> mapEventListener.getNoOfUpdateEvents().get() >= _noOfPuts);

            // Test that the correct number of events were triggered on event listener
            Assert.assertEquals(_noOfPuts, mapEventListener.getNoOfUpdateEvents().get());
          }
          Assert.assertEquals(0, mapEventListener.getNoOfInsertEvents().get());
          Assert.assertEquals(0, mapEventListener.getNoOfRemoveEvents().get());

          mapEventListener.resetCounters();
        },
        () -> {
          IntStream.range(0, _noOfPuts)
              .forEach(
                  i -> {
                    putFunction.apply(i);
                  });
        },
        _noOfRunsToAverage,
        3 * _secondInNanos);
    clientAssetTree.unregisterSubscriber(_mapName, mapEventSubscriber);

    waitFor(() -> subscription.entrySubscriberCount() == 0);
    Assert.assertEquals(0, subscription.entrySubscriberCount());
  }
 @Override
 public PrimitiveIterator.OfInt iterator() {
   if (intermediateType.shouldUseIntermediate(sorted, distinct)) {
     IntStream stream = performIntermediateRemoteOperation(Function.identity());
     return stream.iterator();
   } else {
     return remoteIterator();
   }
 }
Example #12
0
  public static void main(String[] args) {
    SecureRandom secureRandom = new SecureRandom(new byte[] {1, 3, 3, 7});
    int[] randoms =
        IntStream.generate(secureRandom::nextInt).filter(n -> n > 0).limit(10).toArray();
    System.out.println(Arrays.toString(randoms));

    int[] nums = IntStream.iterate(1, n -> n * 2).limit(11).toArray();
    System.out.println(Arrays.toString(nums));
  }
  public static void main(String... args) {

    /*
    -------------------------------------------------------------------------
    From obj to ...
    -------------------------------------------------------------------------
    */
    Stream<String> streamOfStrings = Stream.of("un", "deux", "trois");
    Function<String, StringBuilder> function = StringBuilder::new;
    streamOfStrings.map(function) /*.forEach(System.out::println)*/;
    streamOfStrings = Stream.of("un", "deux", "trois");
    ToIntFunction<String> toIntFunction = String::length;
    IntStream streamOfInts = streamOfStrings.mapToInt(toIntFunction);
    streamOfStrings = Stream.of("un", "deux", "trois");
    ToDoubleFunction<String> toDoubleFunction = String::length;
    DoubleStream streamOfDoubles = streamOfStrings.mapToDouble(toDoubleFunction);
    streamOfStrings = Stream.of("un", "deux", "trois");
    ToLongFunction<String> toLongFunction = String::length;
    LongStream streamOfLongs = streamOfStrings.mapToLong(toLongFunction);

    /*
    -------------------------------------------------------------------------
    From int to ...
    -------------------------------------------------------------------------
    */
    IntUnaryOperator plusplus = i -> i++;
    IntStream.of(1, 2, 3).map(plusplus)
    /*.forEach(x->System.out.println(x))*/ ;
    IntFunction<String> intFunction = i -> "" + i;
    IntStream.of(1, 2, 3).mapToObj(intFunction)
    /*.forEach(System.out::println)*/ ;
    IntToDoubleFunction itdf = i -> i;
    IntStream.of(1, 2, 3).mapToDouble(itdf)
    /*.forEach(System.out::println)*/ ;
    IntToLongFunction itlf = i -> i;
    IntStream.of(1, 2, 3).mapToLong(itlf)
    /*.forEach(System.out::println)*/ ;

    /*
    -------------------------------------------------------------------------
    From long to ...
    -------------------------------------------------------------------------
    */
    LongUnaryOperator times = l -> l * l;
    LongStream.of(1L, 2L, 3L).map(times)
    /*.forEach(System.out::println)*/ ;
    LongFunction<String> lf = l -> "toto";
    LongStream.of(1L, 2L, 3L).mapToObj(lf);

    /*
    -------------------------------------------------------------------------
    From double to ...
    -------------------------------------------------------------------------
    */
    DoubleToIntFunction dtif = d -> (int) d;
    DoubleStream.of(1.3, 1.5, 1.6).mapToInt(dtif).forEach(System.out::println);
  }
Example #14
0
 public static TestSample generate(Random rand, int ins, int outs) {
   return new TestSample(
       IntStream.generate(() -> rand.nextInt(100))
           .limit(ins)
           .mapToObj(Integer::valueOf)
           .collect(Collectors.toList()),
       IntStream.generate(() -> 100 + rand.nextInt(50))
           .limit(outs)
           .mapToObj(Integer::valueOf)
           .collect(Collectors.toList()));
 }
 public void process(Area area, LightProcessor processor) {
   IntStream.rangeClosed(area.getFromX(), area.getToX())
       .forEach(
           x -> {
             IntStream.rangeClosed(area.getFromY(), area.getToY())
                 .forEach(
                     y -> {
                       mLights[x][y] = processor.process(mLights[x][y]);
                     });
           });
 }
Example #16
0
 public void improvementLambdaNegaConvert() {
   IntStream.range(1, h)
       .parallel()
       .filter(i -> i % 3 == 0)
       .forEach(
           e ->
               IntStream.range(1, w)
                   .filter(j -> j % 3 == 0)
                   .parallel()
                   .forEach(f -> improvementNegaProc(f + 1, e + 1)));
 }
Example #17
0
 public void lambdaNegaConvert() {
   /*
   for(int i=0;i<h;i++){
       final int e = i;
       IntStream.range(0,w).parallel().forEach(f -> negaProc(f,e));
   }
   */
   IntStream.range(0, h)
       .parallel()
       .forEach(e -> IntStream.range(0, w).parallel().forEach(f -> negaProc(f, e)));
 }
  @Override
  public void run() {
    int polarization = travelTimeTool.getPolarization();
    boolean psv = false;
    boolean sh = false;
    switch (polarization) {
      case 0:
        psv = true;
        sh = true;
        break;
      case 1:
        psv = true;
        break;
      case 2:
        sh = true;
        break;
      default:
        throw new RuntimeException("Unexpected happens");
    }
    raypaths = new ArrayList<>();
    phases = new ArrayList<>();

    double deltaR = 10; // TODO
    for (Phase phase : targetPhases) {
      if (psv) {
        List<Raypath> possibleRaypathArray =
            RaypathSearch.lookFor(phase, structure, eventR, epicentralDistance, deltaR, true);
        if (possibleRaypathArray.isEmpty()) continue;
        raypaths.addAll(possibleRaypathArray);
        IntStream.range(0, possibleRaypathArray.size()).forEach(i -> phases.add(phase));
      }
      if (sh && phase.pReaches() == null) {
        List<Raypath> possibleRaypathArray =
            RaypathSearch.lookFor(phase, structure, eventR, epicentralDistance, deltaR, false);
        if (possibleRaypathArray.isEmpty()) continue;
        raypaths.addAll(possibleRaypathArray);
        IntStream.range(0, possibleRaypathArray.size()).forEach(i -> phases.add(phase));
      }
    }
    for (int i = 0; i < phases.size(); i++) {
      Phase phase = phases.get(i);
      if (!phase.isDiffracted()) continue;
      Raypath raypath = raypaths.get(i);
      double delta = raypath.computeDelta(phase);
      double dDelta = Math.toDegrees(epicentralDistance - delta);
      phases.set(i, Phase.create(phase.toString() + dDelta));
    }
    int n = raypaths.size();
    // System.out.println("Whats done is done");
    double[] delta = new double[n];
    Arrays.fill(delta, epicentralDistance);
    showResult(delta, raypaths, phases);
  }
Example #19
0
 /**
  * A[N] N is integer in range [2..100,000] each element of A is an integer within range
  * [0..1,000,000]
  *
  * @param A non null, non-empty array
  */
 public int solution(int[] A) {
   // write your code in Java SE 8
   // if there are duplicates, the minimum will be 0
   IntStream numbers = Arrays.stream(A);
   if (numbers.distinct().count() < A.length) {
     return 0;
   } else {
     int firstMin = Arrays.stream(A).min().getAsInt();
     int secondMin = Arrays.stream(A).filter(n -> n != firstMin).min().getAsInt();
     return secondMin - firstMin;
   }
 }
Example #20
0
  public static void main(String[] args) {
    Map<Long, Long> collect =
        IntStream.range(0, 10)
            .mapToObj(Long::valueOf)
            .collect(Collectors.groupingBy(i -> i, reducing((a, b) -> a)));

    System.out.println(collect);

    Map<Long, Long> collect2 =
        IntStream.range(0, 10).mapToObj(Long::valueOf).collect(Collectors.toMap(i -> i, i -> i));
    System.out.println(collect2);
  }
 public long getLightsOnCount() {
   // Stream all X values
   return IntStream.range(0, mLights.length)
       .mapToLong(
           // Stream all Y values and count all the lights that are on
           x ->
               IntStream.range(0, mLights[x].length)
                   .filter(y -> mLights[x][y]) // filter lights on
                   .count() // count items that came through the filter
           )
       .sum();
 }
 private static double[] calculateColumnInverseMeans(RealMatrix matrix) {
   return IntStream.range(0, matrix.getColumnDimension())
       .mapToDouble(
           i ->
               1.0
                   / IntStream.range(0, matrix.getRowDimension())
                       .mapToDouble(j -> matrix.getEntry(j, i))
                       .average()
                       .orElseThrow(
                           () ->
                               new IllegalArgumentException(
                                   "cannot calculate a average for column " + i)))
       .toArray();
 }
  @Override
  public List<T> aggregate(ListOfRanks<T> ranks) {
    int m = ranks.countOfItems();
    double n_ = DoubleStream.of(ranks.weights()).sum();
    double subtrahend = 1 / (double) m;
    double subtrahend2 = 1 / (m * n_);

    double medium = n_ / 2.;
    double[][] ma1 = new double[m][m];
    double[][] ma2 = new double[m][m];
    double[][] ma3 = new double[m][m];

    for (int u = 0; u < m; u++) {
      for (int v = 0; v < m; v++) {
        final int finalU = u;
        final int finalV = v;

        double c =
            ranks
                .stream()
                .filter(rank -> rank.position(finalU) > rank.position(finalV))
                .mapToDouble(rank -> rank.weight)
                .sum();

        if (c > 0) { // MC1
          ma1[u][v] = subtrahend;
        }

        if (c >= medium) { // MC2
          ma2[u][v] = subtrahend;
        }

        ma3[u][v] = c * subtrahend2; // MC3
      }
    }

    double[][] ma;
    switch (type) {
      case MC1:
        ma = ma1;
        break;
      case MC2:
        ma = ma2;
        break;
      default:
        ma = ma3;
    }

    for (int i = 0; i < m; i++) {
      ma[i][i] = 1 - DoubleStream.of(ma[i]).sum();
    }

    double[] weights = findStationaryDistribution(transfer(ma, 0.05));

    return IntStream.range(0, m)
        .mapToObj(i -> Pair.of(weights[i], ranks.itemByNumber(i)))
        .sorted((o1, o2) -> -Double.compare(o1.first, o2.first))
        .map(pair -> pair.second)
        .collect(Collectors.toList());
  }
/**
 * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
 * @version 3.4
 * @since 3.4
 */
public class KnapsackFitnessThreshold {

  private static final double MIN_FITNESS = 7000;
  private static final double MAX_FITNESS = 10900; // 11000;
  private static final int POINTS = 20;

  private static final Params<Double> PARAMS =
      Params.of(
          "Fitness threshold",
          IntStream.rangeClosed(0, POINTS)
              .mapToDouble(i -> MIN_FITNESS + (MAX_FITNESS - MIN_FITNESS) / POINTS * i)
              .mapToObj(Double::valueOf)
              .collect(ISeq.toISeq()));

  private static final Supplier<TrialMeter<Double>> TRIAL_METER =
      () ->
          TrialMeter.of(
              "Fitness threshold",
              "Create fitness threshold performance measures",
              PARAMS,
              "Generation",
              "Fitness",
              "Runtime");

  public static void main(final String[] args) throws InterruptedException {
    final Runner<Double, BitGene, Double> runner =
        Runner.of(threshold -> KNAPSACK, limit::byFitnessThreshold, TRIAL_METER, args);

    runner.start();
    runner.join();
  }
}
  @Test
  public void shouldNotExhaustThreads() throws Exception {
    final ScheduledExecutorService executorService =
        Executors.newScheduledThreadPool(2, testingThreadFactory);
    final GremlinExecutor gremlinExecutor =
        GremlinExecutor.build()
            .executorService(executorService)
            .scheduledExecutorService(executorService)
            .create();

    final AtomicInteger count = new AtomicInteger(0);
    assertTrue(
        IntStream.range(0, 1000)
            .mapToObj(i -> gremlinExecutor.eval("1+1"))
            .allMatch(
                f -> {
                  try {
                    return (Integer) f.get() == 2;
                  } catch (Exception ex) {
                    throw new RuntimeException(ex);
                  } finally {
                    count.incrementAndGet();
                  }
                }));

    assertEquals(1000, count.intValue());

    executorService.shutdown();
    executorService.awaitTermination(30000, TimeUnit.MILLISECONDS);
  }
Example #26
0
 public static List<SimpleEntry<Integer, List<Integer>>> goldbach_list(IntStream range) {
   return range
       .filter(n -> n % 2 == 0)
       .filter(even -> even > 2)
       .mapToObj(even -> new SimpleEntry<>(even, P35.goldbach(even)))
       .collect(toList());
 }
  @Test
  public void int32() {
    Wire wire = createWire();
    wire.write().int32(1);
    wire.write(BWKey.field1).int32(2);
    wire.write(() -> "Test").int32(3);
    checkWire(
        wire,
        "[pos: 0, rlim: 16, wlim: 8EiB, cap: 8EiB ] À⒈Æfield1⒉ÄTest⒊",
        "[pos: 0, rlim: 28, wlim: 8EiB, cap: 8EiB ] À¦⒈٠٠٠Æfield1¦⒉٠٠٠ÄTest¦⒊٠٠٠",
        "[pos: 0, rlim: 11, wlim: 8EiB, cap: 8EiB ] À⒈º⒈⒉º²ñ\\u009E⒈⒊",
        "[pos: 0, rlim: 23, wlim: 8EiB, cap: 8EiB ] À¦⒈٠٠٠º⒈¦⒉٠٠٠º²ñ\\u009E⒈¦⒊٠٠٠",
        "[pos: 0, rlim: 3, wlim: 8EiB, cap: 8EiB ] ⒈⒉⒊",
        "[pos: 0, rlim: 15, wlim: 8EiB, cap: 8EiB ] ¦⒈٠٠٠¦⒉٠٠٠¦⒊٠٠٠");
    checkAsText123(wire);

    // ok as blank matches anything
    AtomicInteger i = new AtomicInteger();
    IntStream.rangeClosed(1, 3)
        .forEach(
            e -> {
              wire.read().int32(i::set);
              assertEquals(e, i.get());
            });

    assertEquals(0, bytes.readRemaining());
    // check it's safe to read too much.
    wire.read();
  }
  @Test
  public void uint16() {
    Wire wire = createWire();
    wire.write().uint16(1);
    wire.write(BWKey.field1).uint16(2);
    wire.write(() -> "Test").uint16(3);
    checkWire(
        wire,
        "[pos: 0, rlim: 16, wlim: 8EiB, cap: 8EiB ] À⒈Æfield1⒉ÄTest⒊",
        "[pos: 0, rlim: 22, wlim: 8EiB, cap: 8EiB ] À¢⒈٠Æfield1¢⒉٠ÄTest¢⒊٠",
        "[pos: 0, rlim: 11, wlim: 8EiB, cap: 8EiB ] À⒈º⒈⒉º²ñ\\u009E⒈⒊",
        "[pos: 0, rlim: 17, wlim: 8EiB, cap: 8EiB ] À¢⒈٠º⒈¢⒉٠º²ñ\\u009E⒈¢⒊٠",
        "[pos: 0, rlim: 3, wlim: 8EiB, cap: 8EiB ] ⒈⒉⒊",
        "[pos: 0, rlim: 9, wlim: 8EiB, cap: 8EiB ] ¢⒈٠¢⒉٠¢⒊٠");
    checkAsText123(wire);

    // ok as blank matches anything
    AtomicInteger i = new AtomicInteger();
    IntStream.rangeClosed(1, 3)
        .forEach(
            e -> {
              wire.read().uint16(i::set);
              assertEquals(e, i.get());
            });

    assertEquals(0, bytes.readRemaining());
    // check it's safe to read too much.
    wire.read();
  }
  @Test
  public void int8() {
    Wire wire = createWire();
    wire.write().int8((byte) 1);
    wire.write(BWKey.field1).int8((byte) 2);
    wire.write(() -> "Test").int8((byte) 3);
    checkWire(
        wire,
        "[pos: 0, rlim: 16, wlim: 8EiB, cap: 8EiB ] À⒈Æfield1⒉ÄTest⒊",
        "[pos: 0, rlim: 19, wlim: 8EiB, cap: 8EiB ] À¤⒈Æfield1¤⒉ÄTest¤⒊",
        "[pos: 0, rlim: 11, wlim: 8EiB, cap: 8EiB ] À⒈º⒈⒉º²ñ\\u009E⒈⒊",
        "[pos: 0, rlim: 14, wlim: 8EiB, cap: 8EiB ] À¤⒈º⒈¤⒉º²ñ\\u009E⒈¤⒊",
        "[pos: 0, rlim: 3, wlim: 8EiB, cap: 8EiB ] ⒈⒉⒊",
        "[pos: 0, rlim: 6, wlim: 8EiB, cap: 8EiB ] ¤⒈¤⒉¤⒊");
    checkAsText123(wire);

    // ok as blank matches anything
    AtomicInteger i = new AtomicInteger();
    IntStream.rangeClosed(1, 3)
        .forEach(
            e -> {
              wire.read().int8(i::set);
              assertEquals(e, i.get());
            });

    assertEquals(0, bytes.readRemaining());
    // check it's safe to read too much.
    wire.read();
  }
  @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());
  }