Reputation: 153
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. So, if duplicates exist, I want to delete both of them. The HashSet only removes the duplicates, so that each value only occurs once. 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.
Upvotes: 1
Views: 260
Reputation: 1127
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);
}
Upvotes: -1
Reputation: 12819
Another possiblilty with Stream
's:
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
. Which returns the List
:
[6, 8, 0]
Upvotes: 2
Reputation: 29730
One solution would be to build a frequency Map
and only retain the keys whose value equals 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:
[0, 6, 8]
Upvotes: 3