0

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 Answers 3

3

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));
}
Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

0
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.