问题描述
我有带有随机整数的ArrayList。如何从此列表中删除一个最小值和最大值?
List < Integer > theBigList = new ArrayList <> ();
Random theGenerator = new Random();
for (int n = 0; n < 14; n++) {
theBigList.add(theGenerator.nextInt(6) + 1);
};
我使用了Colections.max nad minimum方法,但是我认为它从ArrayList中删除了所有最大值和最小值。
在此先感谢您的帮助
解决方法
使用流:
// removes max
theBigList.stream()
.max(Comparator.naturalOrder())
.ifPresent(theBigList::remove);
// removes min
theBigList.stream()
.min(Comparator.naturalOrder())
.ifPresent(theBigList::remove);
没有流:
// removes max
if(!theBigList.isEmpty()) {
theBigList.remove(Collections.max(theBigList));
}
// removes min
if(!theBigList.isEmpty()) {
theBigList.remove(Collections.min(theBigList));
}
,
只需执行此操作。要记住的一点是,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]
,
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));