-1

I have a list like this

[A-Apple.txt,B-Ball.txt,A-Axe.txt,B-Box.txt]

From this I want to create a map like the following:

{A=[A-Apple.txt,A-Axe.txt], B= [B-Ball.txt, B-Box.txt]

I have tried with

   Map<String,List<String>> inputMap = new HashMap<>();
    inputFCSequenceFileList.forEach(value ->{
        List newList = new ArrayList();
                newList.add(value);
                inputMap.put(value.split("-")[0], newList);
            }
            );

But not getting the expected value. I am getting only the last element. And if I move the list creation outside of the foreach loop, then I am getting all the values.

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
Rhea
  • 381
  • 1
  • 7
  • 22

2 Answers2

6

A groupingBy on the stream of the list should give the result you are expecting:

Map<String, List<String>> collect = list.stream()
            .collect(Collectors.groupingBy(s -> s.split("-")[0]));
Loris Securo
  • 7,538
  • 2
  • 17
  • 28
0

you need to check if the list already exists in the map. Only create it if the entry is missing.

inputList = inputMap.getOrDefault(key, new ArrayList<String>());
inputList.add(value);
inputMap.put(key, inputList);

this should do it as loop body. Didnt test it, but should give you the idea.

thst
  • 4,592
  • 1
  • 26
  • 40