简体   繁体   English

字符数组java的arraylist

[英]arraylist of character arrays java

I originally have an arraylist of strings but I want to save it as an arraylist of those strings.toCharArray() instead. 我最初有一个字符串的arraylist但我想把它保存为那些strings.toCharArray()的arraylist。 Is it possible to make an arraylist that stores char arrays? 是否可以制作存储char数组的arraylist? Here is how I tried to implement it. 以下是我尝试实现它的方法。

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());
        }
    }

Note that toCharArray() returns an array of primitives ( char[] ), and not an array of the boxing class ( Character[] as you currently have). 请注意, toCharArray()返回一个基元数组( char[] ),而不是当前拥有的装箱类数组( Character[] )。 Additionally, you're only adding the given array to the map if the length of the array isn't in the map, which probably isn't the behavior you wanted (ie, you should move the line ordered.get(length).add(word.toCharArray()); outside the if statement). 此外,如果数组的长度不在地图中,那么您只是将给定的数组添加到地图中,这可能不是您想要的行为(即,您应该移动行ordered.get(length).add(word.toCharArray());if语句之外)。

Also, note that Java 8's streams can do a lot of the heavy lifting for you: 另外,请注意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));

EDIT: 编辑:
As per the question in the comment, this is also entirely possible in Java 7 without streams: 根据评论中的问题,这在没有流的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