删除重复项(两个值)- ArrayList 中的重复值 [英] Remove duplicates (both values) - duplicate values from an ArrayList

查看:31
本文介绍了删除重复项(两个值)- ArrayList 中的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有以下字符串的 ArrayList

I have an ArrayList with the following strings;

 List<String> e = new ArrayList<String>();
 e.add("123");
 e.add("122");
 e.add("125");
 e.add("123");

我想检查列表中是否有重复项并将其从列表中删除.在这种情况下,我的列表将只有两个值,在本例中它将是值 122 和 125,两个 123 将消失.

I want to check the list for duplicates and remove them from the list. In this case my list will only have two values, and in this example it would be the values 122 and 125, and the two 123s will go away.

最好的方法是什么?我正在考虑使用 Set,但这只会删除其中一个重复项.

What will be the best way to this? I was thinking of using a Set, but that will only remove one of the duplicates.

推荐答案

在 Java 8 中你可以:

In Java 8 you can do:

e.removeIf(s -> Collections.frequency(e, s) > 1);

如果 !Java 8 你可以创建一个 HashMap.如果 String 已经出现在地图中,则将其 key 加一,否则,将其添加到地图中.

If !Java 8 you can create a HashMap<String, Integer>. If the String already appears in the map, increment its key by one, otherwise, add it to the map.

例如:

put("123", 1);

现在让我们假设您再次拥有123",您应该获取密钥的计数并将其加一:

Now let's assume that you have "123" again, you should get the count of the key and add one to it:

put("123", get("aaa") + 1);

现在您可以轻松地在地图上迭代并创建一个新的数组列表,其键值为

2.

Now you can easily iterate on the map and create a new array list with keys that their values are < 2.

参考文献:

这篇关于删除重复项(两个值)- ArrayList 中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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