[英]How to create a unique list of values in Java?
I am trying to create a list, which only consists of unique values. 我正在尝试创建一个仅包含唯一值的列表。
String[] arr = {"5", "5", "7", "6", "7", "8", "0"};
List<String> uniqueList = new ArrayList<String>(new HashSet<String>( Arrays.asList(arr) ));
System.out.println( uniqueList );
What I expect as an output is: 6,8,0. 我期望的输出是:6,8,0。 So, if duplicates exist, I want to delete both of them.
因此,如果存在重复项,我想将它们都删除。 The HashSet only removes the duplicates, so that each value only occurs once.
HashSet仅删除重复项,因此每个值仅出现一次。 However, I want to remove both the numbers, so that I end up with a list, which only has the numbers that occur once in the original list.
但是,我想同时删除两个数字,以便最终得到一个列表,该列表仅具有在原始列表中出现一次的数字。
One solution would be to build a frequency Map
and only retain the keys whose value equals 1
: 一种解决方案是构建一个频率
Map
并且仅保留值等于1
的键:
String[] arr = {"5", "5", "7", "6", "7", "8", "0"};
Arrays.stream(arr)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList()));
One possible value of this List
is: 该
List
一个可能值为:
[0, 6, 8]
Another possiblilty with Stream
's: Stream
的另一个可能性:
List<String> arr1 = Arrays.asList(arr).stream()
.filter(i -> Collections.frequency(Arrays.asList(arr), i) < 2)
.collect(Collectors.toList());
arr1.forEach(System.out::println);
Which will create a filter out all the elements that occur more than once using Collections::frequency
. 这将使用
Collections::frequency
过滤出所有出现多次的所有元素。 Which returns the List
: 返回
List
:
[6, 8, 0]
One other possible solution is collecting the list data into set and then get back to list again. 另一种可能的解决方案是将列表数据收集到集合中,然后再次返回列表。
String[] arr = {"5", "5", "7", "6", "7", "8", "0"};
List<String> stringList = Arrays.stream(arr).collect(Collectors.toSet()).stream().collect(Collectors.toList());
for (String s : stringList) {
System.out.println(s);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.