@Test public void testSummingItemsInAList() { IntSummaryStatistics stats = names.stream().filter(name -> !name.isEmpty()) .collect(Collectors.summarizingInt(name -> name.length())); assertEquals(17, stats.getSum()); assertEquals(2, stats.getMin()); assertEquals(5, stats.getMax()); assertEquals(3.4, stats.getAverage(), 0.01); // Reference method name to call stats = names.stream().filter(name -> !name.isEmpty()).collect(Collectors.summarizingInt(String::length)); assertEquals(17, stats.getSum()); assertEquals(2, stats.getMin()); assertEquals(5, stats.getMax()); assertEquals(3.4, stats.getAverage(), 0.01); }
public void testIntStatistics() { List<IntSummaryStatistics> instances = new ArrayList<>(); instances.add(countTo(1000).stream().collect(Collectors.summarizingInt(i -> i))); instances.add(countTo(1000).stream().mapToInt(i -> i).summaryStatistics()); instances.add(countTo(1000).stream().mapToInt(i -> i).collect(IntSummaryStatistics::new, IntSummaryStatistics::accept, IntSummaryStatistics::combine)); instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingInt(i -> i))); instances.add(countTo(1000).parallelStream().mapToInt(i -> i).summaryStatistics()); instances.add(countTo(1000).parallelStream().mapToInt(i -> i).collect(IntSummaryStatistics::new, IntSummaryStatistics::accept, IntSummaryStatistics::combine)); for (IntSummaryStatistics stats : instances) { assertEquals(stats.getCount(), 1000); assertEquals(stats.getSum(), countTo(1000).stream().mapToInt(i -> i).sum()); assertEquals(stats.getAverage(), (double) stats.getSum() / stats.getCount()); assertEquals(stats.getMax(), 1000); assertEquals(stats.getMin(), 1); } }
@Test public void shouldSmearRotationWeekly() throws Exception { final long hours = Duration.ofDays(7).toHours(); final int[] rotationsPerHour = new int[(int) hours]; final int n = 10000; for (int i = 0; i < n; i++) { long prevEpoch = 0; for (int hour = 0; hour < hours; hour++) { final long nowMillis = TimeUnit.HOURS.toMillis(hour); final long epoch = KubernetesGCPServiceAccountSecretManager.smearedEpoch( nowMillis, "sa" + i + "@example.com"); if (prevEpoch != epoch) { prevEpoch = epoch; rotationsPerHour[hour]++; } } } final IntSummaryStatistics stats = IntStream.of(rotationsPerHour).summaryStatistics(); final double expectedMeanRotationsPerHour = n / hours; assertThat(stats.getAverage(), is(closeTo(expectedMeanRotationsPerHour, expectedMeanRotationsPerHour / 2))); assertThat((double) stats.getMax(), is(lessThan(expectedMeanRotationsPerHour * 2))); }
@Override public int getAsInt() { BinaryOperator<Dimension> accumulator = new BinaryOperator<Dimension>() { @Override public Dimension apply(Dimension t, Dimension u) { int w = Math.max(t.width, u.width); int h = Math.max(t.height, u.height); return new Dimension(w, h); } }; Dimension extent = plantingBlockModel.getPlantingBlocks().stream() .map(pb -> new Dimension( pb.getX() + pb.getColumnCount() - 1, pb.getY() + pb.getRowCount() - 1 )) .reduce(new Dimension(0,0), accumulator); IntSummaryStatistics stats = plantingBlockModel.getPlantingBlocks().stream() .collect(Collectors.summarizingInt(pb -> pb.getColumnCount() * pb.getRowCount())); int maxSize = stats.getMax(); int maxExtent = extent.width * extent.height; return Math.max(maxSize, maxExtent); }
@Test /** Get people statistics: average age, count, maximum age, minimum age and sum og all ages. */ public void getStats() { List<Person> collection = asList(sara4, eva42, viktor40); // Stats stats = Java7Impl.getStats(collection); IntSummaryStatistics stats = collection.stream() // .mapToInt(Person::getAge) // .summaryStatistics(); assertEquals((double) (4 + 40 + 42) / 3, stats.getAverage(),.0001); assertEquals(3, stats.getCount()); assertEquals(42, stats.getMax()); assertEquals(4, stats.getMin()); assertEquals(40 + 42 + 4, stats.getSum()); // collection.stream().mapToInt(Person::getAge).summaryStatistics() }
/** * Given a collection of items and a <code>Predicate</code> to be fulfilled returns an * <code>IntSummaryStatistics</code> over a list of the lengths of segments of successive (as determined by the * order they are returned by the iterator of the collection) items that fulfill the predicate. * * @param coll * the collection of items * @param test * the predicate to fulfill * @param <T> * the type of the items * @return an <code>IntSummaryStatistics</code> over the list of segment lengths */ static <T> IntSummaryStatistics segmentStatistics(Collection<T> coll, Predicate<T> test) { List<Integer> chunkSizes = new ArrayList<>(); int currentSize = 0; for (T item : coll) { boolean p = test.test(item); if (p) { currentSize++; } else { if (currentSize != 0) { chunkSizes.add(currentSize); currentSize = 0; } } } if (currentSize != 0) { chunkSizes.add(currentSize); } return chunkSizes.stream().collect(Collectors.summarizingInt(i -> i)); }
@Test public void testSummarizing() { withRandom(r -> { int[] data = IntStreamEx.of(r, 1000, 1, Integer.MAX_VALUE).toArray(); IntSummaryStatistics expected = IntStream.of(data).summaryStatistics(); IntSummaryStatistics statistics = IntStreamEx.of(data).collect(IntCollector.summarizing()); assertEquals(expected.getCount(), statistics.getCount()); assertEquals(expected.getSum(), statistics.getSum()); assertEquals(expected.getMax(), statistics.getMax()); assertEquals(expected.getMin(), statistics.getMin()); statistics = IntStreamEx.of(data).parallel().collect(IntCollector.summarizing()); assertEquals(expected.getCount(), statistics.getCount()); assertEquals(expected.getSum(), statistics.getSum()); assertEquals(expected.getMax(), statistics.getMax()); assertEquals(expected.getMin(), statistics.getMin()); }); }
/** * @return a number >= 0 if it is present in the output file, otherwise -1 */ private static int getGeneratedInputCountFromOutputLines(List<String> outputLines) { IntSummaryStatistics ints = outputLines.stream() .map(line -> TEST_COUNT_LINE_PATTERN.matcher(line.trim())) .filter(m -> m.matches()) .mapToInt(m -> Integer.parseInt(m.group(1))) .summaryStatistics(); if (ints.getMin() < 0) { throw new RuntimeException("RANDOOP: Number of tests is negative:" + outputLines); } else if (ints.getCount() > 0) { return (int) ints.getSum(); } else { return -1; } }
/** * Categorize the words from the text file into a map, where the map's key * is the length of each word, and the value corresponding to a key is a * count of words of that length. Don't bother with uniqueness or lower- * casing the words. This is the same as the previous exercise except * the map values are the count of words instead of a list of words. * * @throws IOException */ @Test public void ex22_mapLengthToWordCount() throws IOException { Map<Integer, Long> result = reader.lines().flatMap(line -> Arrays.stream(line.split(REGEXP))) .collect(Collectors.groupingBy(s -> s.length(), Collectors.counting())); assertEquals( 1L, (long)result.get(1)); assertEquals(11L, (long)result.get(2)); assertEquals(28L, (long)result.get(3)); assertEquals(21L, (long)result.get(4)); assertEquals(16L, (long)result.get(5)); assertEquals(12L, (long)result.get(6)); assertEquals(10L, (long)result.get(7)); assertEquals( 3L, (long)result.get(8)); assertEquals( 2L, (long)result.get(9)); assertEquals( 2L, (long)result.get(10)); assertEquals( 1L, (long)result.get(11)); IntSummaryStatistics stats = result.keySet().stream().mapToInt(i -> i).summaryStatistics(); assertEquals("min key", 1, stats.getMin()); assertEquals("max key", 11, stats.getMax()); }
/** * Categorize the words from the text file into a map, where the map's key * is the length of each word, and the value corresponding to a key is a * count of words of that length. Don't bother with uniqueness or lower- * casing the words. This is the same as the previous exercise except * the map values are the count of words instead of a list of words. * * @throws IOException */ @Test @Ignore public void ex22_mapLengthToWordCount() throws IOException { Map<Integer, Long> result = null; // TODO assertEquals(1L, (long) result.get(1)); assertEquals(11L, (long) result.get(2)); assertEquals(28L, (long) result.get(3)); assertEquals(21L, (long) result.get(4)); assertEquals(16L, (long) result.get(5)); assertEquals(12L, (long) result.get(6)); assertEquals(10L, (long) result.get(7)); assertEquals(3L, (long) result.get(8)); assertEquals(2L, (long) result.get(9)); assertEquals(2L, (long) result.get(10)); assertEquals(1L, (long) result.get(11)); IntSummaryStatistics stats = result.keySet().stream().mapToInt(i -> i).summaryStatistics(); assertEquals("min key", 1, stats.getMin()); assertEquals("max key", 11, stats.getMax()); }
/** * Categorize the words from the text file into a map, where the map's key * is the length of each word, and the value corresponding to a key is a * count of words of that length. Don't bother with uniqueness or lower- * casing the words. This is the same as the previous exercise except * the map values are the count of words instead of a list of words. * * @throws IOException */ @Test @Ignore public void ex22_mapLengthToWordCount() throws IOException { Map<Integer, Long> result = null; // TODO assertEquals( 1L, (long)result.get(1)); assertEquals(11L, (long)result.get(2)); assertEquals(28L, (long)result.get(3)); assertEquals(21L, (long)result.get(4)); assertEquals(16L, (long)result.get(5)); assertEquals(12L, (long)result.get(6)); assertEquals(10L, (long)result.get(7)); assertEquals( 3L, (long)result.get(8)); assertEquals( 2L, (long)result.get(9)); assertEquals( 2L, (long)result.get(10)); assertEquals( 1L, (long)result.get(11)); IntSummaryStatistics stats = result.keySet().stream().mapToInt(i -> i).summaryStatistics(); assertEquals("min key", 1, stats.getMin()); assertEquals("max key", 11, stats.getMax()); }
@Test public void int_summary_stats_with_stream() { IntSummaryStatistics stats = orderEntries.stream() .mapToInt((x) -> x.getAmount()).summaryStatistics(); // average assertEquals(13.5, stats.getAverage(), 0); // count assertEquals(4, stats.getCount(), 0); // max assertEquals(18, stats.getMax(), 0); // min assertEquals(10, stats.getMin(), 0); // sum assertEquals(54, stats.getSum(), 0); }
@Test public void int_summary_stats_stream_reduction_target() { IntSummaryStatistics stats = orderEntries.stream().collect( Collectors.summarizingInt(OrderEntry::getAmount)); // average assertEquals(13.5, stats.getAverage(), 0); // count assertEquals(4, stats.getCount(), 0); // max assertEquals(18, stats.getMax(), 0); // min assertEquals(10, stats.getMin(), 0); // sum assertEquals(54, stats.getSum(), 0); }
public static void printTrackLengthStatistics(Album album) { IntSummaryStatistics trackLengthStats = album.getTracks() .mapToInt(track -> track.getLength()) .summaryStatistics(); System.out.printf("Max: %d, Min: %d, Ave: %f, Sum: %d", trackLengthStats.getMax(), trackLengthStats.getMin(), trackLengthStats.getAverage(), trackLengthStats.getSum()); }
@Benchmark public Object[] combinedStatisticsJDK_parallel() { DoubleSummaryStatistics stats1 = Person.getJDKPeople().parallelStream().mapToDouble(Person::getHeightInInches).summaryStatistics(); DoubleSummaryStatistics stats2 = Person.getJDKPeople().parallelStream().mapToDouble(Person::getWeightInPounds).summaryStatistics(); IntSummaryStatistics stats3 = Person.getJDKPeople().parallelStream().mapToInt(Person::getAge).summaryStatistics(); return new Object[]{stats1, stats2, stats3}; }
@Benchmark public Object[] combinedStatisticsECStream_parallel() { DoubleSummaryStatistics stats1 = Person.getECPeople().parallelStream().mapToDouble(Person::getHeightInInches).summaryStatistics(); DoubleSummaryStatistics stats2 = Person.getECPeople().parallelStream().mapToDouble(Person::getWeightInPounds).summaryStatistics(); IntSummaryStatistics stats3 = Person.getECPeople().parallelStream().mapToInt(Person::getAge).summaryStatistics(); return new Object[]{stats1, stats2, stats3}; }
@Benchmark public Object[] combinedStatisticsJDK_serial() { DoubleSummaryStatistics stats1 = Person.getJDKPeople().stream().mapToDouble(Person::getHeightInInches).summaryStatistics(); DoubleSummaryStatistics stats2 = Person.getJDKPeople().stream().mapToDouble(Person::getWeightInPounds).summaryStatistics(); IntSummaryStatistics stats3 = Person.getJDKPeople().stream().mapToInt(Person::getAge).summaryStatistics(); return new Object[]{stats1, stats2, stats3}; }
@Benchmark public Object[] combinedStatisticsECLazy_serial() { DoubleSummaryStatistics stats1 = Person.getECPeople().asLazy().collectDouble(Person::getHeightInInches).summaryStatistics(); DoubleSummaryStatistics stats2 = Person.getECPeople().asLazy().collectDouble(Person::getWeightInPounds).summaryStatistics(); IntSummaryStatistics stats3 = Person.getECPeople().asLazy().collectInt(Person::getAge).summaryStatistics(); return new Object[]{stats1, stats2, stats3}; }
@Benchmark public Object[] combinedStatisticsECEager_serial() { DoubleSummaryStatistics stats1 = Person.getECPeople().summarizeDouble(Person::getHeightInInches); DoubleSummaryStatistics stats2 = Person.getECPeople().summarizeDouble(Person::getWeightInPounds); IntSummaryStatistics stats3 = Person.getECPeople().summarizeInt(Person::getAge); return new Object[]{stats1, stats2, stats3}; }
@Benchmark public IntSummaryStatistics uniqueAgesSummaryStatisticsECEager_serial() { MutableIntSet uniqueAges = Person.getECPeople().collectInt(Person::getAge, IntSets.mutable.empty()); IntSummaryStatistics summary = uniqueAges.summaryStatistics(); return summary; }
@Benchmark public IntSummaryStatistics uniqueAgesSummaryStatisticsECLazy_serial() { MutableIntSet uniqueAges = Person.getECPeople().asLazy().collectInt(Person::getAge).toSet(); IntSummaryStatistics summary = uniqueAges.summaryStatistics(); return summary; }
@Benchmark public IntSummaryStatistics uniqueAgesSummaryStatisticsJDK_serial() { final Set<Integer> uniqueAges = Person.getJDKPeople().stream() .mapToInt(Person::getAge) .boxed() .collect(Collectors.toSet()); IntSummaryStatistics summary = uniqueAges.stream().mapToInt(i -> i).summaryStatistics(); return summary; }
@Benchmark public IntSummaryStatistics uniqueAgesSummaryStatisticsECStream_parallel() { MutableIntSet uniqueAges = Person.getECPeople() .parallelStream() .collect(Collectors2.collectInt(Person::getAge, IntSets.mutable::empty)); IntSummaryStatistics summary = uniqueAges.summaryStatistics(); return summary; }
@Benchmark public IntSummaryStatistics uniqueAgesSummaryStatisticsJDK_parallel() { final Set<Integer> uniqueAges = Person.getJDKPeople().parallelStream() .mapToInt(Person::getAge) .boxed() .collect(Collectors.toSet()); IntSummaryStatistics summary = uniqueAges.parallelStream().mapToInt(i -> i).summaryStatistics(); return summary; }
@Test public void ageStatisticsJDK() { IntSummaryStatistics stats = Person.getJDKPeople().stream().mapToInt(Person::getAge).summaryStatistics(); Assert.assertEquals(Person.NUMBER_OF_PEOPLE, stats.getCount()); }
@Test public void ageStatisticsEC() { IntSummaryStatistics stats = Person.getECPeople().asLazy().collectInt(Person::getAge).summaryStatistics(); Assert.assertEquals(Person.NUMBER_OF_PEOPLE, stats.getCount()); }
/** * * Detect the csv separator character from a sample of lines. * The algorithm tries a series of candidate separators * and computes statistics when the separator is used. * * @param lines * @return separator String, or null if the detection algorithm did not succeed */ public String detectSeparator(List<String> lines) { return separators.stream() .map(sep -> new Pair<>(sep, lines.stream().collect(Collectors.summarizingInt(s -> CSVSplitter.split(s, sep).length)))) .filter(p -> { IntSummaryStatistics stats = p.getRight(); return stats.getCount() > 0 && stats.getAverage() >= 2.0 && (stats.getMax() < 2*stats.getAverage()); }).sorted((p1, p2) -> p2.getRight().getMax() - p1.getRight().getMax()) .findFirst().orElse(new Pair<String, IntSummaryStatistics>()).getLeft(); }
private void contributeUserSkills(List<User> users, Info.Builder builder) { IntSummaryStatistics stats = users.stream().mapToInt(u -> u.getSkillsExcludeHidden().size()).summaryStatistics(); Map<String, Double> details = new HashMap<>(); details.put("total", (double) stats.getSum()); details.put("min", (double) stats.getMin()); details.put("max", (double) stats.getMax()); details.put("average", stats.getAverage()); builder.withDetail("personal_skills", details); }
public static void main(String[] args) { Collection<Person> persons = StreamSamples.getPersons(); List<String> names = new ArrayList<>(); persons.stream().map(Person::getFirstName).forEach(names::add) ; List<String> firstNameOfPersons = persons.stream().map(Person::getFirstName) .collect(Collectors.toList()); System.out.println(firstNameOfPersons); Map<Integer, List<Person>> personByAge = persons.stream() .collect(Collectors.groupingBy(Person::getAge)); System.out.println(personByAge); Double averageAge = persons.stream().collect(Collectors.averagingInt(Person::getAge)); System.out.println(averageAge); Long totalPersons = persons.stream().collect(Collectors.counting()); System.out.println(totalPersons); IntSummaryStatistics personsAgeSummary = persons.stream() .collect(Collectors.summarizingInt(Person::getAge)); System.out.println(personsAgeSummary); String allPersonsFirstName = persons.stream() .collect(Collectors.mapping(Person::getFirstName, Collectors.joining("#"))); System.out.println(allPersonsFirstName); // concurrent reduction with parallel stream ConcurrentMap<Integer, List<Person>> personByAgeConcurrent = persons.stream() .collect(Collectors.groupingByConcurrent(Person::getAge)); System.out.println(personByAgeConcurrent); }
@Test public void testCountingItemsInAList() { long count = names.stream().count(); assertEquals(7, count); count = names.stream().filter(name -> !name.isEmpty()).collect(Collectors.counting()); assertEquals(5, count); // A goofy map reduce way IntSummaryStatistics stats = names.stream().filter(name -> !name.isEmpty()).mapToInt(name -> 1) .summaryStatistics(); assertEquals(5, stats.getCount()); }
public void testIntStatistics() { List<IntSummaryStatistics> instances = new ArrayList<>(); instances.add(countTo(1000).stream().collect(Collectors.summarizingInt(i -> i))); instances.add(countTo(1000).stream().mapToInt(i -> i).summaryStatistics()); instances.add(countTo(1000).parallelStream().collect(Collectors.summarizingInt(i -> i))); instances.add(countTo(1000).parallelStream().mapToInt(i -> i).summaryStatistics()); for (IntSummaryStatistics stats : instances) { assertEquals(stats.getCount(), 1000); assertEquals(stats.getSum(), countTo(1000).stream().mapToInt(i -> i).sum()); assertEquals(stats.getMax(), 1000); assertEquals(stats.getMin(), 1); } }
public void testIntCollectNull() { checkNPE(() -> IntStream.of(1).collect(null, IntSummaryStatistics::accept, IntSummaryStatistics::combine)); checkNPE(() -> IntStream.of(1).collect(IntSummaryStatistics::new, null, IntSummaryStatistics::combine)); checkNPE(() -> IntStream.of(1).collect(IntSummaryStatistics::new, IntSummaryStatistics::accept, null)); }
public static void main(String[] args) { //filter过滤器 sorted排序 List<Integer> nums = Arrays.asList(6, 2, 1, 8, 3, 9, 5); List<Integer> filtered = nums.stream().filter(num->num!=-1).sorted().collect(Collectors.toList()); filtered.forEach(System.out::println); //limit 限制条数 Random random = new Random(); random.ints().limit(3).forEach(System.out::println); //map 一对一映射 List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); numbers.stream().map(num->num*num).distinct().collect(Collectors.toList()).forEach(System.out::println); //并行流 List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); strings.parallelStream().filter(string -> !string.isEmpty()).collect(Collectors.toList()).forEach(System.out::println); System.err.println(StringUtils.join(strings.stream().map(fieldName ->"["+fieldName+"]").collect(Collectors.toList()).toArray(), ",")); //统计 List<Integer> aaa= Arrays.asList(3, 2, 2, 3, 7, 3, 5); IntSummaryStatistics stats = aaa.stream().mapToInt((x) -> x).summaryStatistics(); System.out.println("列表中最大的数 : " + stats.getMax()); System.out.println("列表中最小的数 : " + stats.getMin()); System.out.println("所有数之和 : " + stats.getSum()); System.out.println("平均数 : " + stats.getAverage()); }
private static void test4(List<Person> persons) { IntSummaryStatistics ageSummary = persons .stream() .collect(Collectors.summarizingInt(p -> p.age)); System.out.println(ageSummary); // IntSummaryStatistics{count=4, sum=76, min=12, average=19,000000, max=23} }
@Test public void collectSummarizingTest() { // summarizingInt 对 List Integer 集合取最大值,最小值,平均值,总和,总数一次性处理 // 同样的处理 Collectors.summarizingDouble 数组,summarizingLong 数组 IntSummaryStatistics summary = Person.persons() .stream() .filter(n -> n != null) .collect(Collectors.summarizingInt(Person::getAge)); System.out.format("age average: %s, max age: %s, min age: %s, sum age: %s \n", summary.getAverage(), summary.getMax(), summary.getMin(), summary.getSum()); }