Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping By without using a POJO in java 8

I have a use case where I need to read a file and get the grouping of a sequence and a list of values associated with the sequence. The format of these records in the file are like sequence - val , example

10-A
10-B
11-C
11-A

I want the output to be a map (Map<String,List<String>>) with the sequence as the key and list of values associated with it as value, like below

10,[A,B]
11,[C,A]

Is there a way I can do this without creating a POJO for these records? I have been trying to explore the usage of Collectors.groupingBy and most of the examples I see are based on creating a POJO.

I have been trying to write something like this

Map<String, List<String>> seqCpcGroupMap = pendingCpcList.stream().map(rec ->{
  String[] cpcRec = rec.split("-");
  return new Tuple2<>(cpcRec[0],cpcRec[1])
}).collect(Collectors.groupingBy(x->x.))

or

Map<String, List<String>> seqCpcGroupMap = pendingCpcList.stream().map(rec ->{
  String[] cpcRec = rec.split("-");
  return Arrays.asList(cpcRec[0],cpcRec[1]);
}).collect(Collectors.groupingBy(x->(ArrayList<String>)x[0]));

I am unable to provide any key on which the groupingBy can happen for the groupingBy function, is there a way to do this or do I have to create a POJO to use groupingBy?

like image 376
user3679686 Avatar asked Nov 01 '18 16:11

user3679686


2 Answers

You may do it like so,

Map<String, List<String>> result = source.stream()
    .map(s -> s.split("-"))
    .collect(Collectors.groupingBy(a -> a[0], 
        Collectors.mapping(a -> a[1], Collectors.toList())));
like image 183
Ravindra Ranwala Avatar answered Oct 07 '22 14:10

Ravindra Ranwala


Alternatively, you can use Map.computeIfAbsent directly as :

List<String> pendingCpcList = List.of("10-A","10-B","11-C","11-A");
Map<String, List<String>> seqCpcGroupMap = new HashMap<>();
pendingCpcList.stream().map(rec -> rec.split("-"))
        .forEach(a -> seqCpcGroupMap.computeIfAbsent(a[0], k -> new ArrayList<>()).add(a[1]));
like image 31
Naman Avatar answered Oct 07 '22 13:10

Naman