Using Java's built-in Set classes to count EAC

2019-07-15 06:58发布

Given a list that could contain duplicates (like the one below), I need to be able to count Each(keyword) number of unique elements.

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

How do I get the count each unique element from the List? That means i want to know how many "M1" contains in List(list), how many "M2", etc.

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

标签: java list set
5条回答
三岁会撩人
2楼-- · 2019-07-15 07:34

I think you are looking for something like this (I didn't compile it, but it should get you going in the right direction):

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());
}
查看更多
劫难
3楼-- · 2019-07-15 07:38

You are looking for Map<String, Integer> data structure, not Set

Something like

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


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

}

Map is the data structure that maps unique to value

查看更多
神经病院院长
4楼-- · 2019-07-15 07:46

means You want to know how many "M1" contains in List(list), how many "M2", instead of using set interface, you can use the Map interface because Map contain the key, value pair format ,i.e. Map data structure.

 Map<key,Value>
查看更多
Bombasti
5楼-- · 2019-07-15 07:53

Set won't help you in this case, you need a Map:

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));
}
查看更多
小情绪 Triste *
6楼-- · 2019-07-15 07:54

Much easier way: use Collections.frequency()

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

will output

M2: 1

查看更多
登录 后发表回答