1

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.

Shan
  • 75
  • 9
  • Do you want group 1 as the key and all the groups as the value? – jrtapsell Sep 13 '17 at 22:26
  • yes, the pattern matches and get the values from log line as , i need to store Map<, ) - TimeStamp is the Key as well it is the value in the List. – Shan Sep 13 '17 at 23:13
  • Don't you want either a `Multimap` OR a `List>`? I can't see why you need multiple List per key. – charles-allen Sep 14 '17 at 00:46
  • In my Map i need to store 3 values and 1 of the values is also a Key, more info on my above comment. – Shan Sep 14 '17 at 00:52
  • Would a Map>> work too, then you could just use standard Java (with the outer list providing for multiple events at the same timestamp) – jrtapsell Sep 14 '17 at 07:54
  • @Shan - I think you will get better answers if you give more detail on what your `matches` does and what your goal is. Please try to post a minimal example. – charles-allen Sep 14 '17 at 16:08

1 Answers1

1

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.

Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112