0

我的数组列表的值类似于

x-tag
125
154
166
125
125
222
125

在上面的列表中,它具有时间价值1254我有125另一个价值,我可以检查列表是否有 125。但无法找到它出现或出现在列表中的次数

4

4 回答 4

11

使用Collections#frequency()方法:

List<Integer> list = Arrays.asList(125, 154, 166, 125, 125, 222, 125);
int totalCount = Collections.frequency(list, 125);
于 2013-09-30T07:09:25.150 回答
2

您可以使用 Guava 库MultisetMultiset ,彼此相等的元素被称为相同单个元素的出现。

Multiset<Integer> myMultiset = HashMultiset.create();
myMultiset.addAll(list);
System.out.println(myMultiset.count(125)); // 4
于 2013-09-30T07:09:55.023 回答
1
List<Integer> list = Arrays.asList(125,154,166,125,125,222,125);

int count = Collections.frequency(list, 125);

System.out.println("total count: " + tcount);

输出:

total count: 4   
于 2013-09-30T07:12:05.640 回答
1

也可以将其映射到地图中。更多代码:

package com.stackoverflow.counter;

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

public class Count {
    public Map<Integer,Integer> convertToMap(List<Integer> integerList) {
        Map<Integer,Integer> integerMap = new HashMap<>();
        for (Integer i: integerList) {
            Integer numberOfOccurrences = integerMap.get(i);
            if (numberOfOccurrences == null)
                numberOfOccurrences = 0;
            integerMap.put(i,++numberOfOccurrences);
        }
        return integerMap;
    }
    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(1);
        integerList.add(3);
        integerList.add(2);
        integerList.add(1);
        integerList.add(3);
        integerList.add(2);
        integerList.add(4);
        integerList.add(5);
        integerList.add(5);
        Count count = new Count();
        Map<Integer, Integer> integerMap = count.convertToMap(integerList);
        for (Integer i: integerMap.keySet()) {
            System.out.println("Number: " + i + ", found " + integerMap.get(i) + " times.");
        }
    }
}
于 2013-09-30T07:20:48.203 回答