get the duplicates values from Arraylist<String> and then get those items in another Arraylist

自闭症网瘾萝莉.ら 提交于 2019-12-23 04:24:35

问题


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.

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


回答1:


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);
    }
}

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.

Input: [1, 3, 1, 3, 7, 6]

duplicates: [1, 3]

EDITED

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());

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




回答2:


You could also do this via a stream:

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


来源:https://stackoverflow.com/questions/54007206/get-the-duplicates-values-from-arrayliststring-and-then-get-those-items-in-ano

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!