Rhe*_*hea -1 java list hashmap java-8
我有一个这样的清单
[A-Apple.txt,B-Ball.txt,A-Axe.txt,B-Box.txt]
Run Code Online (Sandbox Code Playgroud)
由此我想创建一个如下所示的地图:
{A=[A-Apple.txt,A-Axe.txt], B= [B-Ball.txt, B-Box.txt]
Run Code Online (Sandbox Code Playgroud)
我试过
Map<String,List<String>> inputMap = new HashMap<>();
inputFCSequenceFileList.forEach(value ->{
List newList = new ArrayList();
newList.add(value);
inputMap.put(value.split("-")[0], newList);
}
);
Run Code Online (Sandbox Code Playgroud)
但没有得到预期值。我只得到最后一个元素。如果我将列表创建移到 foreach 循环之外,那么我将获得所有值。
groupingBy列表流上的A应该给出您期望的结果:
Map<String, List<String>> collect = list.stream()
.collect(Collectors.groupingBy(s -> s.split("-")[0]));
Run Code Online (Sandbox Code Playgroud)