英文:
Remove from ArrayList one maximum and minimum value
问题
我有一个包含随机整数的ArrayList。如何从这个列表中删除最小值和最大值?
List<Integer> theBigList = new ArrayList<>();
Random theGenerator = new Random();
for (int n = 0; n < 14; n++) {
theBigList.add(theGenerator.nextInt(6) + 1);
};
我使用了`Collections.max`和`minimum`方法,但我认为它会从ArrayList中删除所有的最大值和最小值。
提前感谢您的帮助。
英文:
I have ArrayList with random Integers. 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.
Thank you in advance for you help
答案1
得分: 3
使用流:
// 删除最大值
theBigList.stream()
.max(Comparator.naturalOrder())
.ifPresent(theBigList::remove);
// 删除最小值
theBigList.stream()
.min(Comparator.naturalOrder())
.ifPresent(theBigList::remove);
不使用流:
// 删除最大值
if (!theBigList.isEmpty()) {
theBigList.remove(Collections.max(theBigList));
}
// 删除最小值
if (!theBigList.isEmpty()) {
theBigList.remove(Collections.min(theBigList));
}
英文:
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));
}
答案2
得分: 2
只需执行此操作。要记住的重点是,List.remove(int)
会删除该索引处的值,而 List.remove(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);
输出
[20]
英文:
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<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]
</details>
# 答案3
**得分**: 0
```java
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));
英文:
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论