2

给定一个可能包含重复项的列表(如下所示),我需要能够计算每个(关键字)唯一元素的数量。

List<String> list = new ArrayList<String>();
Set<String> set = new HashSet<String>();
list.add("M1");
list.add("M1");
list.add("M2");
list.add("M3");

set.addAll(list);
System.out.println(set.size());

如何从列表中获取每个唯一元素的计数?这意味着我想知道 List(list) 中包含多少个“M1”,多少个“M2”等。

The result should be the following:
2 M1
1 M2
1 M3
4

5 回答 5

5

您正在寻找Map<String, Integer>数据结构,而不是Set

就像是

for(iterating over something){ 
    Integer count =map.get(value); 
    if( count == null){
          map.put(value, 1);


    } else{
        count++;
        map.put(value, count);
    }

}

映射是映射唯一值的数据结构

于 2013-08-07T05:01:48.637 回答
2

Set在这种情况下不会帮助你,你需要一个地图:

List<String> list = new ArrayList<String>();
Set<String> set = new HashSet<String>();
list.add("M1");
list.add("M1");
list.add("M2");
list.add("M3");

// ...

Map<String, Integer> counts = new HashMap<String, Integer>();
for(String element: list) {
    int currentCount;
    if(counts.contains(element)) {
        currentCount = counts.get(element) + 1;
    } else {
        currentCount = 1;
    }
    counts.put(element, currentCount);
}

// ...

for(String element: counts.keySet()) {
    System.out.println("element: " + element + ", times appeared: " + counts.get(element));
}
于 2013-08-07T05:06:38.087 回答
2

我认为您正在寻找这样的东西(我没有编译它,但它应该让您朝着正确的方向前进):

List<String> list = ArrayList<>();
Map<String, Integer> counts = new HashMap<>();
// Fill list with values....

for (String item:list) {
    Integer count = counts.get(item);
    if (count == null) {
        // This is the first time we have seen item, so the count should be one.
        count = 1;
    } else {
        // Increment the count by one.
        count = count + 1;
    }
    counts.put(item, count);
}

// Print them all out.
for (Entry<String, Integer> entry : counts.entrySet()) {
    System.out.println(entry.getValue() + " " + entry.getKey());
}
于 2013-08-07T05:11:17.723 回答
0

更简单的方法:使用Collections.frequency()

System.out.println("M2: "+Collections.frequency(list,"M2");

将输出

M2: 1

于 2013-08-07T05:39:50.807 回答
0

意思是你想知道List(list)中有多少个“M1”,有多少个“M2”,不用set接口,可以用 Map接口,因为Map包含键、值对格式,即Map数据结构。

 Map<key,Value>
于 2013-08-07T05:11:34.337 回答