Ejemplo n.º 1
0
  @Test
  public void testMaxAll() {
    List<String> input = Arrays.asList("a", "bb", "c", "", "cc", "eee", "bb", "ddd");
    checkCollector(
        "maxAll",
        Arrays.asList("eee", "ddd"),
        input::stream,
        MoreCollectors.maxAll(Comparator.comparingInt(String::length)));
    Collector<String, ?, String> maxAllJoin =
        MoreCollectors.maxAll(Comparator.comparingInt(String::length), Collectors.joining(","));
    checkCollector("maxAllJoin", "eee,ddd", input::stream, maxAllJoin);
    checkCollector(
        "minAll",
        1L,
        input::stream,
        MoreCollectors.minAll(Comparator.comparingInt(String::length), Collectors.counting()));
    checkCollector(
        "minAllEmpty",
        Arrays.asList(""),
        input::stream,
        MoreCollectors.minAll(Comparator.comparingInt(String::length)));
    checkCollectorEmpty(
        "maxAll",
        Collections.emptyList(),
        MoreCollectors.maxAll(Comparator.comparingInt(String::length)));
    checkCollectorEmpty("maxAllJoin", "", maxAllJoin);

    List<Integer> ints = IntStreamEx.of(new Random(1), 10000, 1, 1000).boxed().toList();
    List<Integer> expectedMax = getMaxAll(ints, Comparator.naturalOrder());
    List<Integer> expectedMin = getMaxAll(ints, Comparator.reverseOrder());
    Collector<Integer, ?, SimpleEntry<Integer, Long>> downstream =
        MoreCollectors.pairing(
            MoreCollectors.first(),
            Collectors.counting(),
            (opt, cnt) -> new AbstractMap.SimpleEntry<>(opt.get(), cnt));

    checkCollector("maxAll", expectedMax, ints::stream, MoreCollectors.maxAll(Integer::compare));
    checkCollector("minAll", expectedMin, ints::stream, MoreCollectors.minAll());
    checkCollector(
        "entry",
        new SimpleEntry<>(expectedMax.get(0), (long) expectedMax.size()),
        ints::stream,
        MoreCollectors.maxAll(downstream));
    checkCollector(
        "entry",
        new SimpleEntry<>(expectedMin.get(0), (long) expectedMin.size()),
        ints::stream,
        MoreCollectors.minAll(downstream));

    Integer a = new Integer(1), b = new Integer(1), c = new Integer(1000), d = new Integer(1000);
    ints = IntStreamEx.range(10, 100).boxed().append(a, c).prepend(b, d).toList();
    for (StreamExSupplier<Integer> supplier : streamEx(ints::stream)) {
      List<Integer> list = supplier.get().collect(MoreCollectors.maxAll());
      assertEquals(2, list.size());
      assertSame(d, list.get(0));
      assertSame(c, list.get(1));

      list = supplier.get().collect(MoreCollectors.minAll());
      assertEquals(2, list.size());
      assertSame(b, list.get(0));
      assertSame(a, list.get(1));
    }
  }