查找arraylist中重复的元素并显示 [英] Find the duplicate elements in arraylist and display

查看:42
本文介绍了查找arraylist中重复的元素并显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我吗?我需要编写一个程序,其中 arraylist 中有 10 个元素,我需要找出它有多少重复值,然后计算并显示这些值.

Can anybody help me? I need to write a program, where I have 10 elements in the arraylist and I need to find the how many duplicate values it has and count and display the values as wel.

例如:说我有

list = {"stack", "overflow", "stack", 
        "yahoo", "google", "msn", 
        "MSN", "stack", "overflow", "user" }

结果应该是:

stack = 3
overflow = 2
google = 1
msn = 2
yahoo =1
user = 1

推荐答案

使用 HashMap.这是一个简单的实现

Use a HashMap. Here is a simple implementation

List<String> strings = new ArrayList<String>();
strings.put("stack", "overflow", "stack", "yahoo", "google", "msn", "MSN", "stack", "overflow", "user");

Map<String, Integer> counts = new HashMap<String, Integer>();

for (String str : strings) {
    if (counts.containsKey(str)) {
        counts.put(str, counts.get(str) + 1);
    } else {
        counts.put(str, 1);
    }
}

for (Map.Entry<String, Integer> entry : counts.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

这篇关于查找arraylist中重复的元素并显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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