简体   繁体   中英

How do you find the smallest value of an ArrayList?

I have an array list called children that has objects that move around certain whole value distances in the GUI and I need to find the smallest of these values and print it to the console.

I'm pretty sure this calls for a for loop right? I just don't know how to structure it correctly to make sure it looks at the values within the "children" ArrayList . Or is there some built in functionality within Eclipse to calculate the smallest value of an array list?

The Collection class has static methods for finding the smallest or the largest element in a Collection. For example:

 System.out.println("max: " + Collections.max(list));
 System.out.println("min: " + Collections.min(list));

If you have and array of positive integer values you can find the smallest one with the following logic:

int [] numbers = {10, 20, 30, 40, 50};
int smallest = numbers[0];
for(int x : numbers ){
   if (x < smallest) {
      smallest = x;
   }
}
System.out.println(smallest);

Something like:

double smallest= children.get(0);
for(double d: children){
    if(smallest > d) smallest=d;

}

You can sort the arraylist using Comparators http://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/

Once it is sorted, pick the first value, it will be smallest one

You're right, you must use loops. You need to take a value out of the list an compare it to all other values. If there is no smaller one, it's the smallest. If there is, you need do check the next one. Java code could soething like this:

numberLoop: for(int number: children){
    for(int numberToCompare: children){
        if(numberToCompare < number)numberLoop.continue;
    }
    System.out.println(number);
    break;
}

PS: It's not Eclipse that's providing the methods. It's basically just a programm to edit text (like Word). The methods are provided by the java API

Using Java 8 Streams ,

Let arr is a array of integers,

int[] arr = new int[]{54,234,1,45,14,54};    
int small = Arrays.stream(arr).reduce((x, y) -> x < y ? x : y).getAsInt();
int large = Arrays.stream(arr).reduce((x, y) -> x > y ? x : y).getAsInt();
System.out.println(small);
System.out.println(large);

You can find the smallest value of an ArrayList using the following ways in JAVA ARRAY List : way 1. Find the smallest value of an ArrayList using the Collection class.

  • you are available with a collection class named min.
  • This method returns the minimum element/value of the specified collection according to the natural ordering of the elements.
  • static <T extends Object & Comparable<? super T> min(Collection<? extends T> c)

Example

package com.javacodeexamples.collections.arraylist;
import java.util.ArrayList;
import java.util.Collections;
public class FindMinValueArrayListExample {
 
    public static void main(String[] args) {
        
        /*
         * ArrayList containing student marks
         */
        ArrayList<Integer> aListMarks = new ArrayList<Integer>();
        
        //add elements to ArrayList
        aListMarks.add(53);
        aListMarks.add(67);
        aListMarks.add(89);
        aListMarks.add(43);
        aListMarks.add(87);
        aListMarks.add(71);
        aListMarks.add(63);
        aListMarks.add(45);
        aListMarks.add(69);
        aListMarks.add(53);
        
        /*
         * To find minimum value in ArrayList, use
         * min method of Collections class.
         */
        
        System.out.println( "ArrayList Min Value: " + Collections.min(aListMarks) );
        
             
    }
}

The output is :

ArrayList Min Value: 43

Way 2: Find the smallest value of an ArrayList using the for loop.

  • You can make use of for loop instead of collections.

Example

package com.javacodeexamples.collections.arraylist;
 
import java.util.ArrayList;
 
public class FindMinValueArrayListExample {
 
    public static void main(String[] args) {
        
        /*
         * ArrayList containing student marks
         */
        ArrayList<Integer> aListMarks = new ArrayList<Integer>();
        
        //add elements to ArrayList
        aListMarks.add(53);
        aListMarks.add(67);
        aListMarks.add(89);
        aListMarks.add(43);
        aListMarks.add(87);
        aListMarks.add(71);
        aListMarks.add(63);
        aListMarks.add(45);
        aListMarks.add(69);
        aListMarks.add(53);
        
        //declare min and max value as the first element of the list
        int min = aListMarks.get(0);
                   
        //declare min and max elements index as 0 (i.e. first element)
        int minIndex = 0;
        
        //Iterate through ArrayList
        for(int i = 1; i < aListMarks.size(); i++ ){
    
             /*
              * If current value is less than min value, it 
              * is new minimum value
              */
            
            if( aListMarks.get(i) < min ){
                min = aListMarks.get(i);
                minIndex = i;
            }
                    
        System.out.println("ArrayList Min Value is: " 
                            + min 
                            + ", Found at index: "
                            + minIndex
                );
 
       }
}

The result is

ArrayList Min Value is: 43, Found at index: 3

For a recursive solution

public static void main(String[] args) {
        int arr[] = {1, 4, 45, 6, -50, 10, 2};
        System.out.println("Minimum value = " + minValue(arr,arr.length));
    }
    
    static int minValue (int arr[], int n){
        if(n == 1){
            return arr[0];
        }
        return Math.min(arr[n-1], minValue(arr,n-1));
    }

This worked for me!

public void minValue() {
    // given
    List<Integer> listOfIntegers = Arrays.asList(1, 2, 3, 4, 56, 7, 89, 10);
    Integer expectedResult = 1;

    // then
    Integer min= listOfIntegers
      .stream()
      .mapToInt(v -> v)
      .min().orElseThrow(NoSuchElementException::new);

    assertEquals("Should be 1", expectedResult, min);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM