Beispiel #1
1
  //	private static void testConnections(GameTile gameTile) {
  //		for(Integer i : GameBoard.getPossibleMoves(true,gameTile.getIndex(), new HashSet<Integer>())){
  //		//for(Integer i : GameBoard.getConnections(gameTile.getIndex())){
  //			System.out.println(i);
  //		}
  //	}
  //
  private static void createAndShowGUI() {
    if (!frame.isPresent()) {
      frame = Optional.of(new JFrame("Chinese Checkers"));
      frame.get().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.get().setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
    }
    frame.get().getContentPane().removeAll();
    frame.get().setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
    // frame.getContentPane().setPreferredSize(new Dimension(1280, 720));
    ArrayList<Box> rows = new ArrayList<Box>();
    ArrayList<JPanel> panes = new ArrayList<JPanel>();

    IntStream.rangeClosed(1, 17).forEachOrdered(i -> rows.add(new Box(BoxLayout.X_AXIS)));

    IntStream.rangeClosed(1, 121)
        .forEachOrdered(
            i -> {
              Box currentRow = null;
              JButton button = new JButton(i + "");
              button.addActionListener(showDestinations());
              button.setPreferredSize(new Dimension(40, 20));
              button.setIconTextGap(0);
              // button.setVisible(true);
              button.setOpaque(true);
              if (i < 2) {
                currentRow = rows.get(0);
              } else if (i < 4) {
                currentRow = rows.get(1);
              } else if (i < 7) {
                currentRow = rows.get(2);
              } else if (i < 11) {
                currentRow = rows.get(3);
              } else if (i < 24) {
                currentRow = rows.get(4);
              } else if (i < 36) {
                currentRow = rows.get(5);
              } else if (i < 47) {
                currentRow = rows.get(6);
              } else if (i < 57) {
                currentRow = rows.get(7);
              } else if (i < 66) {
                currentRow = rows.get(8);
              } else if (i < 76) {
                currentRow = rows.get(9);
              } else if (i < 87) {
                currentRow = rows.get(10);
              } else if (i < 99) {
                currentRow = rows.get(11);
              } else if (i < 112) {
                currentRow = rows.get(12);
              } else if (i < 116) {
                currentRow = rows.get(13);
              } else if (i < 119) {
                currentRow = rows.get(14);
              } else if (i < 121) {
                currentRow = rows.get(15);
              } else {
                currentRow = rows.get(16);
              }
              currentRow.add(button);
              switch (GameBoard.board.get(i - 1).getPlayer()) {
                case 1:
                  button.setBackground(Color.red);
                  break;
                case 2:
                  button.setBackground(Color.blue);
                  break;
                case 3:
                  button.setBackground(Color.yellow);
                  break;
                case 4:
                  button.setBackground(Color.green);
                  break;
                case 5:
                  button.setBackground(Color.BLACK);
                  break;
                case 6:
                  button.setBackground(Color.white);
                  break;
                case 7:
                  button.setBackground(Color.gray);
                  GameBoard.board.get(i - 1).setPlayer(0);
                  break;
                default:
                  button.setBackground(Color.LIGHT_GRAY);
                  break;
              }
            });

    IntStream.rangeClosed(1, 17)
        .forEachOrdered(
            i -> {
              panes.add((new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0))));
              panes.get(i - 1).setPreferredSize(new Dimension(1280, 20));
            });

    panes.parallelStream().forEach(p -> p.add(rows.get(panes.indexOf(p))));
    panes.stream().forEachOrdered(p -> frame.get().add(p));
    frame.get().setPreferredSize(new Dimension(1280, 720));
    frame.get().setResizable(false);
    frame.get().pack();
    frame.get().setVisible(true);
    frame.get().validate();
    frame.get().repaint();
  }
Beispiel #2
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();
 }
 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]);
                     });
           });
 }
/**
 * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
 * @version 3.4
 * @since 3.4
 */
public class KnapsackExecutionTime {

  private static final double GEN_BASE = pow(10, log10(100) / 20.0);
  private static final Params<Long> PARAMS =
      Params.of(
          "Execution time",
          IntStream.rangeClosed(1, 50)
              .mapToLong(i -> max((long) pow(GEN_BASE, i), i))
              .mapToObj(Long::new)
              .collect(ISeq.toISeq()));

  private static final Supplier<TrialMeter<Long>> TRIAL_METER =
      () ->
          TrialMeter.of(
              "Execution time",
              "Create execution time performance measures",
              PARAMS,
              "Generation",
              "Fitness",
              "Runtime");

  public static void main(final String[] args) throws InterruptedException {
    final Runner<Long, BitGene, Double> runner =
        Runner.of(
            KNAPSACK,
            duration -> limit.byExecutionTime(Duration.ofMillis(duration)),
            TRIAL_METER,
            args);

    runner.start();
    runner.join();
  }
}
Beispiel #5
0
 public Collection<Integer> getRtcWorkItemRange() {
   String rangesString = props.getProperty(RTC_WORKITEM_ID_RANGE);
   String[] ranges = rangesString.split(",");
   IntStream intStream = IntStream.of();
   for (String range : ranges) {
     String[] splitted = range.split("\\.\\.");
     int from = Integer.parseInt(splitted[0].trim());
     if (splitted.length == 1) {
       intStream = IntStream.concat(intStream, IntStream.rangeClosed(from, from));
     } else {
       int to = Integer.parseInt(splitted[1].trim());
       intStream = IntStream.concat(intStream, IntStream.rangeClosed(from, to));
     }
   }
   return intStream.boxed().collect(Collectors.toList());
 }
  public static List generateFizzBuzz(int number1, int number2) {
    List<String> myList = new ArrayList<>();

    return IntStream.rangeClosed(number1, number2)
        .mapToObj(i -> generateFizzBuzz(i))
        .collect(Collectors.toList());
  }
  @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 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();
  }
/**
 * @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 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();
  }
 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;
 }
Beispiel #12
0
  public static void main(String[] args) {
    FooBarQix fbq = new FooBarQix();

    IntStream.rangeClosed(1, 100)
        .forEachOrdered(
            (i) -> {
              System.out.printf("%s\n", fbq.doFooBarQix(i));
            });
  }
Beispiel #13
0
  @Test
  public void select_groups_by_query_paginated() {
    IntStream.rangeClosed(0, 9)
        .forEach(i -> groupDb.insertGroup(newGroupDto().setName(i + "-name")));

    assertThat(
            underTest.selectGroupNamesByPermissionQuery(
                dbSession, PermissionQuery.builder().setPageIndex(2).setPageSize(3).build()))
        .containsExactly("3-name", "4-name", "5-name");
  }
  public List<String> getWorkload() {
    Config config = vampires.getConfig("workload");
    String task = config.getString("task");
    int startCount = config.getInt("start");
    int stopCount = config.getInt("stop");

    return IntStream.rangeClosed(startCount, stopCount)
        .mapToObj(i -> String.format(task, i))
        .collect(Collectors.toList());
  }
  public static void main(String[] args) {

    // Page 45
    // ========

    IntStream.iterate(1, i -> i * 2).limit(10).forEachOrdered(System.out::println);

    IntStream.range(1, 6).forEach(System.out::print); // prints 123456

    // Page 46
    // ========

    List<Integer> intList = Arrays.asList(1, 2, 3);

    OptionalDouble maxDistance =
        intList.stream().map(i -> new Point(i % 3, i / 3)).mapToDouble(p -> p.distance(0, 0)).max();

    DoubleStream ds =
        intList.stream().map(i -> new Point(i % 3, i / 3)).mapToDouble(p -> p.distance(0, 0));

    OptionalDouble maxDistance1 = ds.max();

    // Page 48
    // ========

    Optional<Integer> max =
        Arrays.asList(1, 2, 3, 4, 5).stream().map(i -> i + 1).max(Integer::compareTo);

    // Page 49
    // ========

    OptionalInt max1 = IntStream.rangeClosed(1, 5).map(i -> i + 1).max();

    DoubleStream ds1 = IntStream.rangeClosed(1, 10).asDoubleStream();

    Stream<Integer> is = IntStream.rangeClosed(1, 10).boxed();

    Stream<Integer> integerStream = Stream.of(1, 2);
    IntStream is1 = integerStream.mapToInt(Integer::intValue);
  }
 /** {@inheritDoc} */
 @Override
 public void insertUsers(final Integer size) {
   log.info("Create {} users", size);
   // lock to update max user id
   try {
     lock.writeLock().lock();
     userDao.insertUsers(IntStream.rangeClosed(1, size).boxed().collect(Collectors.toList()));
     this.max = userDao.max();
   } finally {
     lock.writeLock().unlock();
   }
   log.info("{} users are inserted. Max id is {}", size, max);
 }
Beispiel #17
0
  public static void main(String... args) {

    List<Integer> numbers = Arrays.asList(3, 4, 5, 1, 2);

    Arrays.stream(numbers.toArray()).forEach(System.out::println);
    int calories = Dish.menu.stream().mapToInt(Dish::getCalories).sum();
    System.out.println("Number of calories:" + calories);

    // max and OptionalInt
    OptionalInt maxCalories = Dish.menu.stream().mapToInt(Dish::getCalories).max();

    int max;
    if (maxCalories.isPresent()) {
      max = maxCalories.getAsInt();
    } else {
      // we can choose a default value
      max = 1;
    }
    System.out.println(max);

    // numeric ranges
    IntStream evenNumbers = IntStream.rangeClosed(1, 100).filter(n -> n % 2 == 0);

    System.out.println(evenNumbers.count());

    Stream<int[]> pythagoreanTriples =
        IntStream.rangeClosed(1, 100)
            .boxed()
            .flatMap(
                a ->
                    IntStream.rangeClosed(a, 100)
                        .filter(b -> Math.sqrt(a * a + b * b) % 1 == 0)
                        .boxed()
                        .map(b -> new int[] {a, b, (int) Math.sqrt(a * a + b * b)}));

    pythagoreanTriples.forEach(t -> System.out.println(t[0] + ", " + t[1] + ", " + t[2]));
  }
    public StatisticalValidationState() {
      ValidatorFactory factory = null;
      final Configuration<?> configuration = Validation.byDefaultProvider().configure();
      try (InputStream mappingStream =
          StatisticalValidation.class.getResourceAsStream("mapping.xml")) {
        configuration.addMapping(mappingStream);
        factory = configuration.buildValidatorFactory();
        assertThat(factory).isNotNull();
      } catch (IOException e) {
        e.printStackTrace();
      }

      validator = factory.getValidator();

      entitiesUnderTest =
          IntStream.rangeClosed(0, NUMBER_OF_TEST_ENTITIES)
              .mapToObj(index -> new TestEntity(index % 10))
              .collect(Collectors.toList());
    }
Beispiel #19
0
  public static Config getConfigForKey(Config config, String... keys) {
    // generate all the keys from least specific to most specific
    // foo, bar baz -> foo, foo.bar, foo.bar.baz
    Config mergedConfig = config;

    List<String> strings = Arrays.asList(keys);
    List<String> resolvedKeys =
        IntStream.rangeClosed(1, keys.length)
            .boxed()
            .map(i -> Joiner.on(".").join(strings.subList(0, i)))
            .collect(Collectors.toList());

    resolvedKeys = Lists.reverse(resolvedKeys);

    for (String key : resolvedKeys) {
      Config fromKey = config.getConfig(key);
      mergedConfig = mergedConfig.withFallback(fromKey);
    }

    return mergedConfig;
  }
/**
 * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
 * @version 3.5
 * @since 3.5
 */
public class KnapsackSelectorComparison {

  private static final double GEN_BASE = pow(10, log10(100) / 20.0);
  private static final Params<Long> PARAMS =
      Params.of(
          "Fixed generation",
          IntStream.rangeClosed(1, 50)
              .mapToLong(i -> max((long) pow(GEN_BASE, i), i))
              .mapToObj(Long::valueOf)
              .collect(ISeq.toISeq()));

  private static final Supplier<TrialMeter<Long>> TRIAL_METER =
      () ->
          TrialMeter.of(
              "Fixed generation",
              "Create fixed generation performance measures",
              PARAMS,
              "Generation1",
              "Fitness1",
              "Runtime1",
              "Generation2",
              "Fitness2",
              "Runtime2");

  public static void main(final String[] args) throws InterruptedException {
    final Runner2<Long, BitGene, Double> runner =
        Runner2.of(
            KNAPSACK.builder().selector(new MonteCarloSelector<>()).build(),
            limit::byFixedGeneration,
            KNAPSACK,
            limit::byFixedGeneration,
            TRIAL_METER,
            args);

    runner.start();
    runner.join();
  }
}
  @Test
  public void float64() {
    Wire wire = createWire();
    wire.write().float64(1);
    wire.write(BWKey.field1).float64(2);
    wire.write(() -> "Test").float64(3);
    checkWire(
        wire,
        "[pos: 0, rlim: 16, wlim: 8EiB, cap: 8EiB ] À⒈Æfield1⒉ÄTest⒊",
        "[pos: 0, rlim: 40, wlim: 8EiB, cap: 8EiB ] À\\u0091٠٠٠٠٠٠ð?Æfield1\\u0091٠٠٠٠٠٠٠@ÄTest\\u0091٠٠٠٠٠٠⒏@",
        "[pos: 0, rlim: 11, wlim: 8EiB, cap: 8EiB ] À⒈º⒈⒉º²ñ\\u009E⒈⒊",
        "[pos: 0, rlim: 35, wlim: 8EiB, cap: 8EiB ] À\\u0091٠٠٠٠٠٠ð?º⒈\\u0091٠٠٠٠٠٠٠@º²ñ\\u009E⒈\\u0091٠٠٠٠٠٠⒏@",
        "[pos: 0, rlim: 3, wlim: 8EiB, cap: 8EiB ] ⒈⒉⒊",
        "[pos: 0, rlim: 27, wlim: 8EiB, cap: 8EiB ] \\u0091٠٠٠٠٠٠ð?\\u0091٠٠٠٠٠٠٠@\\u0091٠٠٠٠٠٠⒏@");
    checkAsText123(wire);

    // ok as blank matches anything
    class Floater {
      double f;

      public void set(double d) {
        f = d;
      }
    }
    Floater n = new Floater();
    IntStream.rangeClosed(1, 3)
        .forEach(
            e -> {
              wire.read().float64(n::set);
              assertEquals(e, n.f, 0.0);
            });

    assertEquals(0, bytes.readRemaining());
    // check it's safe to read too much.
    wire.read();
  }
 private static List<String> createRandomDocuments(int howMany) {
   Random rand = new Random();
   Json.ObjectMapperExt mapper = Json.mapper();
   return IntStream.rangeClosed(0, howMany - 1)
       .mapToObj(
           (x) -> {
             ObjectNode node = mapper.createObjectNode();
             node.put("generated", "generated-" + rand.nextInt());
             node.put("idx", x);
             node.put("rand", rand.nextInt());
             return node;
           })
       .map(
           (doc) -> {
             try {
               ODocument d = DocumentService.create(TEST_COLLECTION, doc);
               return d.<String>field("id");
             } catch (Throwable throwable) {
               return null;
             }
           })
       .filter(Objects::nonNull)
       .collect(Collectors.toList());
 }
Beispiel #23
0
 public static void multiples() {
   int multiples3And5 = IntStream.rangeClosed(1, 999).filter(i -> i % 3 == 0 || i % 5 == 0).sum();
   System.out.println(multiples3And5);
 }
Beispiel #24
0
 private Set<Integer> intSet(final int size) {
   return IntStream.rangeClosed(1, size).mapToObj(Integer::valueOf).collect(Collectors.toSet());
 }
  @Test
  public void testFlatMapping() {
    {
      Map<Integer, List<Integer>> expected =
          IntStreamEx.rangeClosed(1, 100)
              .boxed()
              .toMap(x -> IntStreamEx.rangeClosed(1, x).boxed().toList());
      Collector<Integer, ?, Map<Integer, List<Integer>>> groupingBy =
          Collectors.groupingBy(
              Function.identity(),
              MoreCollectors.flatMapping(
                  x -> IntStream.rangeClosed(1, x).boxed(), Collectors.toList()));
      checkCollector(
          "flatMappingSimple", expected, () -> IntStreamEx.rangeClosed(1, 100).boxed(), groupingBy);
    }

    Function<Entry<String, List<String>>, Stream<String>> valuesStream =
        e -> e.getValue() == null ? null : e.getValue().stream();
    List<Entry<String, List<String>>> list =
        EntryStream.of(
                "a", Arrays.asList("bb", "cc", "dd"), "b", Arrays.asList("ee", "ff"), "c", null)
            .append("c", Arrays.asList("gg"), "b", null, "a", Arrays.asList("hh"))
            .toList();
    {
      Map<String, List<String>> expected =
          EntryStream.of(list.stream())
              .flatMapValues(l -> l == null ? null : l.stream())
              .grouping();
      checkCollector(
          "flatMappingCombine",
          expected,
          list::stream,
          Collectors.groupingBy(
              Entry::getKey, MoreCollectors.flatMapping(valuesStream, Collectors.toList())));
      AtomicInteger openClose = new AtomicInteger();
      Collector<Entry<String, List<String>>, ?, Map<String, List<String>>> groupingBy =
          Collectors.groupingBy(
              Entry::getKey,
              MoreCollectors.flatMapping(
                  valuesStream.andThen(
                      s -> {
                        if (s == null) return null;
                        openClose.incrementAndGet();
                        return s.onClose(openClose::decrementAndGet);
                      }),
                  Collectors.toList()));
      checkCollector(
          "flatMappingCombineClosed",
          expected,
          list::stream,
          MoreCollectors.collectingAndThen(
              groupingBy,
              res -> {
                assertEquals(0, openClose.get());
                return res;
              }));
      boolean catched = false;
      try {
        Collector<Entry<String, List<String>>, ?, Map<String, List<String>>> groupingByException =
            Collectors.groupingBy(
                Entry::getKey,
                MoreCollectors.flatMapping(
                    valuesStream.andThen(
                        s -> {
                          if (s == null) return null;
                          openClose.incrementAndGet();
                          return s.onClose(openClose::decrementAndGet)
                              .peek(
                                  e -> {
                                    if (e.equals("gg")) throw new IllegalArgumentException(e);
                                  });
                        }),
                    Collectors.toList()));
        list.stream()
            .collect(
                MoreCollectors.collectingAndThen(
                    groupingByException,
                    res -> {
                      assertEquals(0, openClose.get());
                      return res;
                    }));
      } catch (IllegalArgumentException e1) {
        assertEquals("gg", e1.getMessage());
        catched = true;
      }
      assertTrue(catched);
    }
    {
      Map<String, List<String>> expected =
          EntryStream.of(
                  "a", Arrays.asList("bb"), "b", Arrays.asList("ee"), "c", Arrays.asList("gg"))
              .toMap();
      Collector<Entry<String, List<String>>, ?, List<String>> headOne =
          MoreCollectors.flatMapping(valuesStream, MoreCollectors.head(1));
      checkCollector(
          "flatMappingSubShort",
          expected,
          list::stream,
          Collectors.groupingBy(Entry::getKey, headOne));
      checkShortCircuitCollector(
          "flatMappingShort",
          expected,
          4,
          list::stream,
          MoreCollectors.groupingBy(Entry::getKey, StreamEx.of("a", "b", "c").toSet(), headOne));
      AtomicInteger cnt = new AtomicInteger();
      Collector<Entry<String, List<String>>, ?, List<String>> headPeek =
          MoreCollectors.flatMapping(
              valuesStream.andThen(s -> s == null ? null : s.peek(x -> cnt.incrementAndGet())),
              MoreCollectors.head(1));
      assertEquals(
          expected, StreamEx.of(list).collect(Collectors.groupingBy(Entry::getKey, headPeek)));
      assertEquals(3, cnt.get());
      cnt.set(0);
      assertEquals(
          expected,
          StreamEx.of(list)
              .collect(
                  MoreCollectors.groupingBy(
                      Entry::getKey, StreamEx.of("a", "b", "c").toSet(), headPeek)));
      assertEquals(3, cnt.get());
    }
    {
      Map<String, List<String>> expected =
          EntryStream.of(
                  "a",
                  Arrays.asList("bb", "cc"),
                  "b",
                  Arrays.asList("ee", "ff"),
                  "c",
                  Arrays.asList("gg"))
              .toMap();
      Collector<Entry<String, List<String>>, ?, List<String>> headTwo =
          MoreCollectors.flatMapping(valuesStream, MoreCollectors.head(2));
      checkCollector(
          "flatMappingSubShort",
          expected,
          list::stream,
          Collectors.groupingBy(Entry::getKey, headTwo));
      AtomicInteger openClose = new AtomicInteger();
      boolean catched = false;
      try {
        Collector<Entry<String, List<String>>, ?, Map<String, List<String>>> groupingByException =
            Collectors.groupingBy(
                Entry::getKey,
                MoreCollectors.flatMapping(
                    valuesStream.andThen(
                        s -> {
                          if (s == null) return null;
                          openClose.incrementAndGet();
                          return s.onClose(openClose::decrementAndGet)
                              .peek(
                                  e -> {
                                    if (e.equals("gg")) throw new IllegalArgumentException(e);
                                  });
                        }),
                    MoreCollectors.head(2)));
        list.stream()
            .collect(
                MoreCollectors.collectingAndThen(
                    groupingByException,
                    res -> {
                      assertEquals(0, openClose.get());
                      return res;
                    }));
      } catch (IllegalArgumentException e1) {
        assertEquals("gg", e1.getMessage());
        catched = true;
      }
      assertTrue(catched);
    }
  }
 private static Population<DoubleGene, Double> population(final int min, final int max) {
   return IntStream.rangeClosed(min, max)
       .mapToDouble(i -> (double) i)
       .mapToObj(FitnessThresholdLimitTest::phenotype)
       .collect(Population.toPopulation());
 }