如何计算 ArrayList 中的元素在另一个 ArrayList 中出现的频率?

alv*_*ira 5 java compare arraylist count

我想计算来自 ArrayList“list1”的元素在另一个 ArrayList“list2”中出现的频率。

我想要这个输出:

A 2
B 0
C 1
D 2
Run Code Online (Sandbox Code Playgroud)

我得到这个输出:

A 0
B 0
C 0
D 69
Run Code Online (Sandbox Code Playgroud)

你能帮我做这个吗?谢谢!

enter code here

    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    ArrayList<Character> list1 = new ArrayList<Character>();
    ArrayList<Character> list2 = new ArrayList<Character>();

    Collections.addAll(list1, 'A', 'B', 'C', 'D');
    Collections.addAll(list2, 'D', 'A', 'C', 'A', 'D');

    for (int i = 0; i < list1.size(); i++) {

        for (int j = 0; j < list2.size(); j++) {
            

            if (list1.get(i) == list2.get(j)) {
                map.put(list1.get(i), 1);
            } 
            
            if (list1.get(i) == list2.get(j) && (map.containsKey(list1.get(i)))) {
                map.replace(list1.get(i), list1.get(i) + 1);
            } 
            
            if (list1.get(i) != list2.get(j)) {
                map.put(list1.get(i), 0);
            }
            
        } 
    }

    
    System.out.println("Map: ");
    for (Map.Entry<Character, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
Run Code Online (Sandbox Code Playgroud)

dre*_*ash 8

使用该方法frequency,从收集,即:

    for (Character c : list1)
       map.put(c, Collections.frequency(list2, c));

    System.out.println("Map: ");
    for (Map.Entry<Character, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
Run Code Online (Sandbox Code Playgroud)

如果你是一个班轮的粉丝:

    list1.forEach(c -> map.put(c, Collections.frequency(list2, c)));
Run Code Online (Sandbox Code Playgroud)

包括元素的打印:

list1.forEach(c ->  System.out.printf("%s %d%n", c, Collections.frequency(list2, c)));
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您的原始答案几乎是正确的,您只需要重新考虑条件句及其顺序:

 for (Character c1 : list1) {
    for (Character c2 : list2) {
        if(map.containsKey(c1) && c1 == c2 ){
           map.put(c1, map.get(c1) + 1);
        }
        else if (!map.containsKey(c1) && c1 != c2 ) {
            map.put(c1, 0);
        } 
        else if (!map.containsKey(c1) && c1 == c2) {
            map.put(c1, 1);
        } 
    } 
}
Run Code Online (Sandbox Code Playgroud)

另一个建议是,如果您不明确需要循环索引,最好使用习惯用法for (Character c1 : list1)而不是for(int i = 0; i < list1.size(); i++). 第一个版本比第二个版本更干净,更不容易出错。此外,您可以使用变量c1而不必一直这样做list1.get(i)