Example usage for java.util.stream Collectors groupingBy

List of usage examples for java.util.stream Collectors groupingBy

Introduction

In this page you can find the example usage for java.util.stream Collectors groupingBy.

Prototype

public static <T, K, D, A, M extends Map<K, D>> Collector<T, ?, M> groupingBy(
        Function<? super T, ? extends K> classifier, Supplier<M> mapFactory,
        Collector<? super T, A, D> downstream) 

Source Link

Document

Returns a Collector implementing a cascaded "group by" operation on input elements of type T , grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector .

Usage

From source file:Main.java

public static <T, K, V> HashMap<K, HashSet<V>> group(Collection<T> entities, Function<T, K> keyMapper,
        Function<T, V> valueMapper) {
    return entities.stream().collect(Collectors.groupingBy(keyMapper, HashMap::new,
            Collectors.mapping(valueMapper, Collectors.toCollection(HashSet::new))));
}

From source file:com.mgmtp.perfload.perfalyzer.reporting.ReportCreator.java

public void createReport(final List<PerfAlyzerFile> files) throws IOException {
    Function<PerfAlyzerFile, String> classifier = perfAlyzerFile -> {
        String marker = perfAlyzerFile.getMarker();
        return marker == null ? "Overall" : marker;
    };//from ww w  . j  a  va2  s . c  om
    Supplier<Map<String, List<PerfAlyzerFile>>> mapFactory = () -> new TreeMap<>(Ordering.explicit(tabNames));

    Map<String, List<PerfAlyzerFile>> filesByMarker = files.stream()
            .collect(Collectors.groupingBy(classifier, mapFactory, toList()));

    Map<String, SortedSetMultimap<String, PerfAlyzerFile>> contentItemFiles = new LinkedHashMap<>();

    for (Entry<String, List<PerfAlyzerFile>> entry : filesByMarker.entrySet()) {
        SortedSetMultimap<String, PerfAlyzerFile> contentItemFilesByMarker = contentItemFiles.computeIfAbsent(
                entry.getKey(),
                s -> TreeMultimap.create(new ItemComparator(reportContentsConfigMap.get("priorities")),
                        Ordering.natural()));

        for (PerfAlyzerFile perfAlyzerFile : entry.getValue()) {
            File file = perfAlyzerFile.getFile();
            String groupKey = removeExtension(file.getPath());
            boolean excluded = false;
            for (Pattern pattern : reportContentsConfigMap.get("exclusions")) {
                Matcher matcher = pattern.matcher(groupKey);
                if (matcher.matches()) {
                    excluded = true;
                    log.debug("Excluded from report: {}", groupKey);
                    break;
                }
            }
            if (!excluded) {
                contentItemFilesByMarker.put(groupKey, perfAlyzerFile);
            }
        }
    }

    // explicitly copy it because it is otherwise filtered from the report in order to only show in the overview
    String loadProfilePlot = new File("console", "[loadprofile].png").getPath();
    copyFile(new File(soureDir, loadProfilePlot), new File(destDir, loadProfilePlot));

    Map<String, List<ContentItem>> tabItems = new LinkedHashMap<>();
    Map<String, QuickJump> quickJumps = new HashMap<>();
    Set<String> tabNames = contentItemFiles.keySet();

    for (Entry<String, SortedSetMultimap<String, PerfAlyzerFile>> tabEntry : contentItemFiles.entrySet()) {
        String tab = tabEntry.getKey();
        SortedSetMultimap<String, PerfAlyzerFile> filesForTab = tabEntry.getValue();

        List<ContentItem> contentItems = tabItems.computeIfAbsent(tab, list -> new ArrayList<>());
        Map<String, String> quickJumpMap = new LinkedHashMap<>();
        quickJumps.put(tab, new QuickJump(tab, quickJumpMap));

        int itemIndex = 0;
        for (Entry<String, Collection<PerfAlyzerFile>> itemEntry : filesForTab.asMap().entrySet()) {
            String title = itemEntry.getKey();
            Collection<PerfAlyzerFile> itemFiles = itemEntry.getValue();

            TableData tableData = null;
            String plotSrc = null;
            for (PerfAlyzerFile file : itemFiles) {
                if ("png".equals(getExtension(file.getFile().getName()))) {
                    plotSrc = file.getFile().getPath();
                    copyFile(new File(soureDir, plotSrc), new File(destDir, plotSrc));
                } else {
                    tableData = createTableData(file.getFile());
                }
            }

            // strip off potential marker
            title = substringBefore(title, "{");

            String[] titleParts = split(title, SystemUtils.FILE_SEPARATOR);
            StringBuilder sb = new StringBuilder(50);
            String separator = " - ";
            sb.append(resourceBundle.getString(titleParts[0]));
            sb.append(separator);
            sb.append(resourceBundle.getString(titleParts[1]));

            List<String> fileNameParts = extractFileNameParts(titleParts[1], true);
            if (titleParts[1].contains("[distribution]")) {
                String operation = fileNameParts.get(1);
                sb.append(separator);
                sb.append(operation);
            } else if ("comparison".equals(titleParts[0])) {
                String operation = fileNameParts.get(1);
                sb.append(separator);
                sb.append(operation);
            } else if (titleParts[1].contains("[gclog]")) {
                if (fileNameParts.size() > 1) {
                    sb.append(separator);
                    sb.append(fileNameParts.get(1));
                }
            }

            title = sb.toString();
            ContentItem item = new ContentItem(tab, itemIndex, title, tableData, plotSrc,
                    resourceBundle.getString("report.topLink"));
            contentItems.add(item);

            quickJumpMap.put(tab + "_" + itemIndex, title);
            itemIndex++;
        }
    }

    NavBar navBar = new NavBar(tabNames, quickJumps);
    String testName = removeExtension(testMetadata.getTestPlanFile());
    OverviewItem overviewItem = new OverviewItem(testMetadata, resourceBundle, locale);
    Content content = new Content(tabItems);

    String perfAlyzerVersion;
    try {
        perfAlyzerVersion = Resources.toString(Resources.getResource("perfAlyzer.version"), Charsets.UTF_8);
    } catch (IOException ex) {
        log.error("Could not read perfAlyzer version from classpath resource 'perfAlyzer.version'", ex);
        perfAlyzerVersion = "";
    }

    String dateTimeString = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withLocale(locale)
            .format(ZonedDateTime.now());
    String createdString = String.format(resourceBundle.getString("footer.created"), perfAlyzerVersion,
            dateTimeString);
    HtmlSkeleton html = new HtmlSkeleton(testName, createdString, navBar, overviewItem, content);
    writeReport(html);
}