我有一个ArrayList
其中包含一些重复的值和出现三次的元素,我想将那些出现三次的值专门收集到另一个中ArrayList
like
Arraylist<String> strings; //contains all strings that are duplicates and that occur thrice
在这里,我只想获取在另一个数组列表中出现三次的字符串。
Arraylist<String> thrice; //contains only elements that occur three times.
目前,我有一个solution https://stackoverflow.com/questions/54007206/get-the-duplicates-values-from-arrayliststring-and-then-get-those-items-in-ano用于处理重复项,但我无法扩展它以仅获取出现三次的字符串,这请帮助我找出答案。
您可以通过流来完成此操作,如下所示:
List<String> result = strings.stream()
.collect(Collectors.groupingBy(Function.identity(), counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 3) // keep only elements that occur 3 times
.map(Map.Entry::getKey)
.collect(Collectors.toList());
您也可以按如下方式执行此操作,但我建议使用上面的方法,因为它更可取。
List<String> result = new HashSet<>(strings).stream()
.filter(item -> strings.stream()
.filter(e -> e.equals(item)).limit(3).count() == 3)
.collect(Collectors.toList());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)