Using Java's built-in Set classes to count EACH(keyword) unique element in List values from a list

不想你离开。 提交于 2019-12-13 16:23:05

问题


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

回答1:


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



回答2:


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




回答3:


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



回答4:


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>



回答5:


Much easier way: use Collections.frequency()

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

will output

M2: 1



来源:https://stackoverflow.com/questions/18094993/using-javas-built-in-set-classes-to-count-eachkeyword-unique-element-in-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!