Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在列表中添加与java中映射键匹配的元素_Java_List_Java 8_Hashmap - Fatal编程技术网

如何在列表中添加与java中映射键匹配的元素

如何在列表中添加与java中映射键匹配的元素,java,list,java-8,hashmap,Java,List,Java 8,Hashmap,我有一张这样的清单 [A-Apple.txt,B-Ball.txt,A-Axe.txt,B-Box.txt] 由此,我想创建一个如下所示的地图: {A=[A-Apple.txt,A-Axe.txt], B= [B-Ball.txt, B-Box.txt] 我试过了 Map<String,List<String>> inputMap = new HashMap<>(); inputFCSequenceFileList.forEach(value

我有一张这样的清单

[A-Apple.txt,B-Ball.txt,A-Axe.txt,B-Box.txt]
由此,我想创建一个如下所示的地图:

{A=[A-Apple.txt,A-Axe.txt], B= [B-Ball.txt, B-Box.txt]
我试过了

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

但是没有得到期望值。我只得到最后一个元素。如果我将列表创建移到foreach循环之外,那么我将获得所有值。

您需要检查列表是否已经存在于映射中。仅当条目丢失时才创建它

inputList = inputMap.getOrDefault(key, new ArrayList<String>());
inputList.add(value);
inputMap.put(key, inputList);
这应该作为循环体来完成。没有测试它,但应该给你一个想法。

列表流中的groupingBy应该给出你期望的结果:

Map<String, List<String>> collect = list.stream()
            .collect(Collectors.groupingBy(s -> s.split("-")[0]));