Converting List To Maps in Java 8

337 Views Asked by At

I am loading a log file as input stream and need to do aggregate processing on the matching values on each line, also I need to store duplicates while saving the lines in MultiMap, I am finding trouble collecting the below stream stored into List as Multimap<String, List<String>>

try (Stream<String> stream = Files.lines(Paths.get(inFileName))) {
    List<String> matchedValues = stream
                    .flatMap(s -> MultiPatternSpliterator.matches(s, p1))
                    .map(r -> r.group(1))
                    .collect(Collectors.toList());

    matchedValues.forEach(System.out::println);
}

How to convert the same to store the values in Map with duplicate values.

1

There are 1 best solutions below

0
On

It's hard to say what you really want, but given that you say you need "log line as <reTimeStamp, reHostName, reServiceTime>" to be stored as "Map<<reTimeStamp>, <reTimeStamp, reHostName, reServiceTime>" I'd go with:

        Map<String, List<String>> matchedValues = stream
                .flatMap(MultiPatternSpliterator::matches)
                .map(r -> Arrays.asList(r.group(1), r.group(2), r.group(3)))
                .collect(Collectors.toMap(
                        groups -> groups.get(0),
                        Function.identity()));

If key (i.e. timestamp) can be duplicated, use (List)Multimap which would give you a list of lists per key:

        ListMultimap<String, List<String>> matchedValues = stream
                .flatMap(MultiPatternSpliterator::matches)
                .map(r -> Arrays.asList(r.group(1), r.group(2), r.group(3)))
                .collect(toImmutableListMultimap(
                        groups -> groups.get(0),
                        Function.identity()));

I would be easier if you showed some example input and output.