简体   繁体   中英

Comparing int to arraylist of integer

I have an int element and I would like to know if this int is higher than all the integers of an Arraylist ?

Example :

int a ; // Contain an int (i.e 51 or 54 or 989...etc)

ArrayList<Integer> list = new ArrayList<Integer>(); // contain a list of Integers

My purpose is to know if a is higher than any number in the arraylist.

Thanks in advance

Sorting is complete overkill. You just need to compare your value to the highest value in the list. Here's a way to do this with existing library functions:

if (a > Collections.max(list)) {
   //a is higher than anything in list
}

Note:

This carries a caveat of always going through the whole list even if the very first element is larger than a . But it's a tradeoff you're usually willing to make because the code reads so nice. If you really want the early exit, you can roll your own approach like in Austin's answer, or in Java 8, it would look something like this:

if ( list.stream().allMatch(element -> a > element) ) {
  //...a is higher than anything in list
}

you can just iterate the array to see if any other value is higher..

int a = _whateverInt ; // Contain an int (i.e 51 or 54 or 989...etc)

ArrayList<Integer> list = new ArrayList<Integer>();
boolean isHigher = true;
for(int i = 0; i < list.size() && isHigher; i ++)
{
    isHigher = a > list.get(i);

}

Solution 1:

public class Test {
    public static void main(String[] args) {
        int a = 150;

        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        arrayList.add(50);
        arrayList.add(100);
        arrayList.add(30);

        System.out.println(a > Collections.max(arrayList));
    }
}

Solution 2:

public class Test {
    public static void main(String[] args) {
        int a = 150;

        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        arrayList.add(50);
        arrayList.add(100);
        arrayList.add(30);

        Collections.sort(arrayList);
        System.out.println(a > arrayList.get(arrayList.size() - 1));
    }
}
int a;

ArrayList<Integer> list = new ArrayList<Integer>();

int max = Collections.max(list);

if(a>max)
{
//this is what you want
}

Hope you find this useful... edit: oops someone already answered the same trick :(

private boolean isLargest(int a, ArrayList<Integer> list)
{
   ArrayList<Integer> sortedList = Collections.sort(list);
   if(a > sortedList.get(0))
      return true;
   return false;
}

It is not efficient, but this approach leaves the ordering in the original list in-tact.

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