簡體   English   中英

字符數組java的arraylist

[英]arraylist of character arrays java

我最初有一個字符串的arraylist但我想把它保存為那些strings.toCharArray()的arraylist。 是否可以制作存儲char數組的arraylist? 以下是我嘗試實現它的方法。

String[] words = new String[]{"peter","month","tweet", "pete", "twee", "pet", "et"};
    HashMap<Integer,ArrayList<Character[]>> ordered = new HashMap<>();

    int length = 0;
    int max = 0; //max Length of words left

    for(String word: words){

        if(ordered.containsKey(length) == false){ //if int length key doesnt exist yet
             ordered.put(length, new ArrayList<Character[]>()); //put key in hashmap with value of arraylist with the one value
             ordered.get(length).add(word.toCharArray());
        }
    }

請注意, toCharArray()返回一個基元數組( char[] ),而不是當前擁有的裝箱類數組( Character[] )。 此外,如果數組的長度不在地圖中,那么您只是將給定的數組添加到地圖中,這可能不是您想要的行為(即,您應該移動行ordered.get(length).add(word.toCharArray());if語句之外)。

另外,請注意Java 8的流可以為您做很多繁重的工作:

String[] words = new String[]{"peter","month","tweet", "pete", "twee", "pet", "et"};
Map<Integer, List<char[]>> ordered =
    Arrays.stream(word)
          .map(String::toCharArray)
          .collect(Collectors.groupingBy(x -> x.length));

編輯:
根據評論中的問題,這在沒有流的Java 7中也是完全可能的:

String[] words = new String[]{"peter","month","tweet", "pete", "twee", "pet", "et"};
Map<Integer, List<char[]>> ordered = new HashMap<>();

for (String word: words) {
    int length = words.length();

    // if int length key doesnt exist in the map already
    List<char[]> list = orderd.get(length);
    if (list == null) {
        list = new ArrayList<>();
        orderd.put(length, list);
    }
    list.add(word);
}

暫無
暫無

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

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