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

查看:35
本文介绍了从 Arraylist<String> 中获取重复值然后在另一个 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");

在这里,我想获取另一个数组列表中的所有重复值...

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,这意味着该元素没有被添加到 set 中,即它已经存在于那里.

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 是计数.然后你过滤这个 map 中计数大于 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<String> 中获取重复值然后在另一个 Arraylist 中获取这些项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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