'How to remove duplicate highs and lows
I want to remove duplicates of the maximum and minimum values from a collection of integers. I can delete if there is 1 duplicate, but how can I remove when collection contains more then one?
values.stream()
.sorted(Comparator.reverseOrder())
.skip(1)
.sorted()
.skip(1)
.collect(Collectors.toList())
.forEach(System.out::println);
}
Solution 1:[1]
Lets consider you have List<Integer> asList = Arrays.asList(2, 2, 4, 6, 7, 8, 7, 8);
You can create 2 different streams for your solution. First you will have to find out min & max using following way:
IntSummaryStatistics stats = asList.stream().mapToInt(Integer::intValue).summaryStatistics();
This will return you min & max. Once you get both the value you can try to filter out the record and collect all the remaining.
List<Integer> collect = asList.stream()
.filter(x -> x > stats.getMin() && x < stats.getMax())
.collect(Collectors.toList());
collect.add(stats.getMin());
collect.add(stats.getMax());
You will get the required output once you sort the list: [2, 4, 6, 7, 7, 8]
Solution 2:[2]
List<Integer> numbersList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
Collections.sort(numbersList);
int min = numbersList.get(0);
int max = numbersList.get(numbersList.size() - 1);
numbersList = numbersList.subList(numbersList.lastIndexOf(min), numbersList.size());
int maxIdx = numbersList.lastIndexOf(max);
while (maxIdx != -1) {
numbersList.remove(maxIdx);
maxIdx = numbersList.lastIndexOf(max);
}
System.out.println(numbersList);
o/p: [1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | I'm_Pratik |
| Solution 2 | AkSh |
