必须得到字符串ArrayList中的字母数

时间:2015-09-23 05:34:31

标签: java arraylist

如果给我一个字符串的ArrayList,即{"hello", "goodbye", "morning", "night"},我该如何检查abc等的数量,等等。列表中有?

该方法必须返回int s的数组,其中position [0]是a的数字等。例如,returnArray[1] = 1,因为有一个b列表中的public static int[] getLetters( ArrayList<String> list) { int [] result = new int[25]; if(list.contains('a')) { result[0] = result[0] + 1; } return result; } 。有没有比仅仅硬编码每个字母更好的方法呢?

public class Something
{
   private Time cls = new Time();

   public Something(int companyId)
   {
      cls.LoadSettings1(companyId);
   }

   public void CallMethod1()
   {
      cls.Method1();
   }
}

有没有比再重复上述策略25次更好的方法?

4 个答案:

答案 0 :(得分:8)

您可以使用char作为解决数组的方法,例如......

ArrayList<String> list = new ArrayList<>(Arrays.asList(new String[]{"hello", "goodbye", "morning", "night"}));
int[] results = new int[26];
for (String value : list) {
    for (char c : value.toCharArray()) {
         // 'a' is the lowest range (0), but the ascii for 'a' is 97
        results[c - 'a'] += 1;
    }
}

导致......

[0, 1, 0, 1, 2, 0, 3, 2, 2, 0, 0, 2, 1, 3, 4, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0]

nb:这只适用于小写字符,如果你有任何大写字符,你将得到一个数组越界错误。您可以为每个字符添加范围检查,以确保它在az之间,但这取决于您

答案 1 :(得分:0)

Yo可以将您的数组转换为CharArray(),然后您可以将每个字母与您想要的字母进行比较。

答案 2 :(得分:0)

您可以依赖mapCharacter课程,如下所示:

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

class C {
    public static void main(String[] args) {
        String w1 = "samefoo";
        String w2 = "barsame";

        ArrayList<String> al = new ArrayList<String>();
        al.add(w1);
        al.add(w2);

        // this is your method --->
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        for(String str: al) {
            for(int i = 0; i < str.length(); ++i) {
                char k = str.charAt(i);
                if(map.containsKey(k)) {
                    map.put(k, map.get(k) + 1);
                } else {
                    map.put(k, 1);
                }
            }
        }
        // <---

        for(char c: map.keySet()) {
            System.out.println(c + ":" + map.get(c));
        }
    }
}

显然,不在地图中的所有人都隐含地将0作为计数器。

答案 3 :(得分:0)

使用java 8,你可以这样做:

List<String> list = new ArrayList<>(Arrays.asList("hello", "goodbye", "morning", "night"));

Map<String, Long> map = list.stream()
    .flatMap(word -> Arrays.stream(word.split("")))
    .collect(Collectors.groupingBy(
        letter -> letter, 
        Collectors.counting()));

System.out.println(map); // {r=1, b=1, t=1, d=1, e=2, g=3, h=2, i=2,
                         // y=1, l=2, m=1, n=3, o=4}

从这张地图构建所需的数组留作读者的练习;)

相关问题