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

查看:121
本文介绍了删除重复项(两个值) - 从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,Integer> 。如果字符串已经出现在地图中,则将其增加1,否则,将其添加到地图中。

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#removeIf
  • Collections#frequency
  • HashMap

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

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