从Arraylist< String>获取重复值.然后将这些项目放在另一个Arraylist中 [英] get the duplicates values from Arraylist<String> and then get those items in another Arraylist

查看:94
本文介绍了从Arraylist< String>获取重复值.然后将这些项目放在另一个Arraylist中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个arraylist,其中包含一些重复的值,我想将这些值收集到另一个Arraylist中. 喜欢

I have an arraylist which contains some values with duplicates i want to collect those values into another Arraylist.... like

 Arraylist<String> one;   //contains all values with duplicates
  one.add("1");
  one.add("2");
  one.add("2");
  one.add("2");

在这里,我想在另一个arraylist中获取所有重复值...

Here, I want to get all the duplicates values in another arraylist...

Arraylist<String> duplicates;    //contains all duplicates values which is 2.

我想要那些大于或等于3的值.

I want those values which counts greater or equals 3.....

当前,我对此没有任何解决方案,请帮助我找出答案

Currently, I don't have any solution for this please help me to find out

推荐答案

您可以为此使用一个集合:

You can use a set for this:

Set<String> set = new HashSet<>();
List<String> duplicates = new ArrayList<>();

for(String s: one) {
    if (!set.add(s)) {
        duplicates.add(s);
    }
}

您只需将所有元素添加到集合中即可.如果方法add()返回false,则表示该元素未添加到集合中,即该元素已经存在.

You just keep adding all the elements to the set. If method add() returns false, this means the element was not added to set i.e it already exists there.

输入:[1, 3, 1, 3, 7, 6]

重复:[1, 3]

已编辑

对于等于或大于3的值,您可以像这样使用流来做到这一点:

For the value which counts 3 or greater, you can use streams to do it like so:

List<String> collect = one.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .entrySet()
            .stream()
            .filter(e -> e.getValue() >= 3)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

基本上,您是在地图中收集初始列表的,其中key是字符串,而value是计数.然后,您可以过滤此地图以获取计数值大于3的值,并将其收集到结果列表中

Basically you collect you initial list in a map, where key is the string and value is the count. Then you filter this map for values that have count greater than 3, and collect it to the result list

这篇关于从Arraylist&lt; String&gt;获取重复值.然后将这些项目放在另一个Arraylist中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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