簡體   English   中英

將項目添加到 HashMap 內的 ArrayList

[英]Add items to an ArrayList inside a HashMap

我正在嘗試創建一個 HashMap,它通過字符的 ArrayList 並將字符作為鍵返回,並將值作為 ArrayList oof 索引返回,例如[X,X,Y,Z,X]將返回地圖喜歡 :

{
  X: [0,1,4];
  Y: [2];
  Z: [3];
}

我有這段代碼,但它不起作用,因為 add 方法返回一個布爾值,我需要返回一個新列表:

/* 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) => [...v,i]的操作

Java中有類似的東西嗎?

您可以簡單地執行以下操作:

mapOfPatternCharsIndex.computeIfPresent(listOfPatternChars.get(i), (k,v) -> {v.add(i); return v;} );

以下是否可以接受?

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {

    public static void main(String[] args) {
        Map<Character, List<Integer>> map = new HashMap<>();
        String userPattern = "XXYZX";
        for (int i = 0; i < userPattern.length(); i++) {
            Character key = userPattern.charAt(i);
            List<Integer> indexes = map.get(key);
            if (indexes == null) {
                indexes = new ArrayList<>();
            }
            indexes.add(i);
            map.put(key, indexes);
        }
        System.out.println(map);
    }
}

運行上面的代碼會產生以下輸出:

{X=[0, 1, 4], Y=[2], Z=[3]}

您可以使用IntStreamCollectors.groupingBy從列表中獲取所有字符及其對應的索引。

List<Character> charList = Arrays.asList('X', 'X', 'Y', 'Z', 'X');

Map<Character, List<Integer>> map = IntStream.range(0, charList.size())
        .boxed()
        .collect(Collectors.groupingBy(charList::get));

System.out.println(map);

輸出:

{X=[0, 1, 4], Y=[2], Z=[3]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM