[英]Remove from ArrayList one maximum and minimum value
I have ArrayList with random Integers.我有带有随机整数的 ArrayList。 How can I remove from this list one minmum value and maximum value?如何从此列表中删除一个最小值和最大值?
List < Integer > theBigList = new ArrayList <> ();
Random theGenerator = new Random();
for (int n = 0; n < 14; n++) {
theBigList.add(theGenerator.nextInt(6) + 1);
};
I used method Colections.max nad minimum but I think it removes all of maximum and minimum values from ArrayList.我使用了方法 Colections.max nad minimum 但我认为它从 ArrayList 中删除了所有最大值和最小值。
Thank you in advance for you help预先感谢您的帮助
With streams:使用流:
// removes max
theBigList.stream()
.max(Comparator.naturalOrder())
.ifPresent(theBigList::remove);
// removes min
theBigList.stream()
.min(Comparator.naturalOrder())
.ifPresent(theBigList::remove);
Without streams:没有流:
// removes max
if(!theBigList.isEmpty()) {
theBigList.remove(Collections.max(theBigList));
}
// removes min
if(!theBigList.isEmpty()) {
theBigList.remove(Collections.min(theBigList));
}
Just do this.就这样做吧。 The point to remember is that List.remove(int)
removes the value at that index where List.remove(object)
removes the object.要记住的一点是List.remove(int)
删除了 List.remove List.remove(object)
删除 object 的索引处的值。
List<Integer> theBigList = new ArrayList<>(List.of(10,20,30));
if (theBigList.size() >= 2) {
Integer max = Collections.max(theBigList);
Integer min = Collections.min(theBigList);
theBigList.remove(max);
theBigList.remove(min);
}
System.out.println(theBigList);
Prints印刷
[20]
List< Integer > theBigList = new ArrayList<>();
theBigList.remove(
theBigList
.stream()
.mapToInt(v -> v)
.max().orElseThrow(NoSuchElementException::new));
theBigList.remove(
theBigList
.stream()
.mapToInt(v -> v)
.min().orElseThrow(NoSuchElementException::new));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.