@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 testMapping() { List<String> input = Arrays.asList("Capital", "lower", "Foo", "bar"); Collector<String, ?, Map<Boolean, Optional<Integer>>> collector = MoreCollectors.partitioningBy( str -> Character.isUpperCase(str.charAt(0)), MoreCollectors.mapping(String::length, MoreCollectors.first())); checkShortCircuitCollector( "mapping", new BooleanMap<>(Optional.of(7), Optional.of(5)), 2, input::stream, collector); Collector<String, ?, Map<Boolean, Optional<Integer>>> collectorLast = MoreCollectors.partitioningBy( str -> Character.isUpperCase(str.charAt(0)), MoreCollectors.mapping(String::length, MoreCollectors.last())); checkCollector( "last", new BooleanMap<>(Optional.of(3), Optional.of(3)), input::stream, collectorLast); input = Arrays.asList("Abc", "Bac", "Aac", "Abv", "Bbc", "Bgd", "Atc", "Bpv"); Map<Character, List<String>> expected = EntryStream.of('A', Arrays.asList("Abc", "Aac"), 'B', Arrays.asList("Bac", "Bbc")).toMap(); AtomicInteger cnt = new AtomicInteger(); Collector<String, ?, Map<Character, List<String>>> groupMap = Collectors.groupingBy( s -> s.charAt(0), MoreCollectors.mapping( x -> { cnt.incrementAndGet(); return x; }, MoreCollectors.head(2))); checkCollector("groupMap", expected, input::stream, groupMap); cnt.set(0); assertEquals(expected, input.stream().collect(groupMap)); assertEquals(4, cnt.get()); }