将项目添加到hashmap中的阵列列表中
我正在尝试创建一个通过字符列表进行的hashmap 例如[X,X,X,Y,Z,X]
将返回图:
{
X: [0,1,4];
Y: [2];
Z: [3];
}
我有此代码,但它不起作用,因为添加方法返回布尔值,我需要返回新的列表:
/* turn the pattern into a List of characters
turn the List into a HashMap with the keys as the characters and
the values as the indexes of the characters in the List
*/
ArrayList<Character> listOfPatternChars = convertStringToCharList(userPattern);
HashMap<Character,ArrayList<Integer>> mapOfPatternCharsIndex = new HashMap<Character,ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> arrayOfIndexes = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < listOfPatternChars.size(); i++) {
mapOfPatternCharsIndex.putIfAbsent(listOfPatternChars.get(i), new ArrayList<Integer>());
mapOfPatternCharsIndex.computeIfPresent(listOfPatternChars.get(i), (k,v) -> v.add(i) );
}
我猜在JavaScript中,我可以使用传播操作员并执行(k,v)=&gt之类的操作。 [... v,i]
Java中有类似的东西吗?
I'm trying to create a HashMap that goes through an ArrayList of characters and returns the characters as keys and the values as an ArrayList oof indexes where they showed up
for example [X,X,Y,Z,X]
would return a map like :
{
X: [0,1,4];
Y: [2];
Z: [3];
}
I have this code but it`s not working because the add method returns a boolean and I need to return a new List:
/* turn the pattern into a List of characters
turn the List into a HashMap with the keys as the characters and
the values as the indexes of the characters in the List
*/
ArrayList<Character> listOfPatternChars = convertStringToCharList(userPattern);
HashMap<Character,ArrayList<Integer>> mapOfPatternCharsIndex = new HashMap<Character,ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> arrayOfIndexes = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < listOfPatternChars.size(); i++) {
mapOfPatternCharsIndex.putIfAbsent(listOfPatternChars.get(i), new ArrayList<Integer>());
mapOfPatternCharsIndex.computeIfPresent(listOfPatternChars.get(i), (k,v) -> v.add(i) );
}
I guess in JavaScript I could use the spread operator and do something like (k, v) => [...v,i]
is there anything similar in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以简单地做类似的事情:
You can simply do something like:
以下是可以接受的吗?
运行上述代码会产生以下输出:
Is the following acceptable?
Running the above code produces the following output:
您可以将
intstream
与collectors.groupingby
一起从列表中获取所有字符及其相应的索引。输出:
You can use
IntStream
withCollectors.groupingBy
to fetch all the characters and their corresponding indices from the list.Output: