使用Java的内置Set类对列表中列表值中的EACH(关键字)唯一元素进行计数 [英] Using Java's built-in Set classes to count EACH(keyword) unique element in List values from a list

查看:179
本文介绍了使用Java的内置Set类对列表中列表值中的EACH(关键字)唯一元素进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

我认为您正在寻找类似的东西(我没有对其进行编译,但是它应该使您朝着正确的方向前进):

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

这篇关于使用Java的内置Set类对列表中列表值中的EACH(关键字)唯一元素进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆