0

please help!

I have a class like this:

public class Person {
    private int age
}

Assume that i have an ArrayList of Person type and i want to take out 15 Persons with max age sort by descending order of age. I can sort the list and then take out the value but if the List has about a thousand objects inside, it take too much time. Which way i can do this faster?

Thank you. Sorry about my english!

tuankhoa1996
  • 131
  • 4
  • 18
  • You can do a **partial** bubble sort. – PM 77-1 Mar 28 '16 at 04:34
  • It would of course depend on what you're doing, but are you sure it's the sort that takes too much time? Sorting one million objects in an ArrayList on my not-very-new computer using the plain `sort` provided by Java8 takes about 8ms, a thousand isn't even easily measurable. – Joachim Isaksson Mar 28 '16 at 04:45
  • Possible duplicate of [how to get maximum value from the List/ArrayList](http://stackoverflow.com/questions/8304767/how-to-get-maximum-value-from-the-list-arraylist) – Abrar Jahin Mar 28 '16 at 05:16

5 Answers5

0

Try to:

  1. Override hashcode() method to be more efficient (you should override equals() as well)
  2. Use TreeSet instead of ArrayList - it keeps objects sorted.
0

If you dont need to re-sort your list, just a loop through every item I create a sample solution with an array and you can apply to your list, just re-write your comparator

public static void main(String[] args) {
    int[] a = { 3, 4, 5, 2, 3, 4, 1, 2, 4, 5, 6, 7, 4, 3, 5, 7, 2, 7 };
    int countMax = 0;
    int max = -1;
    for (int i = 0; i < a.length; i++) {
        if (max < a[i]) {
            countMax = 1;
            max = a[i];
        } else if (max == a[i]) {
            countMax++;
        }
    }
    System.out.println(countMax);
}
VinhNT
  • 1,091
  • 8
  • 13
0

You may try to measure.

public List<Person> findMaxAge15(List<Person> persons) {
    return persons.sorted(Comparator.comparing(Person::getAge).reversed())
        .limit(15)
        .collect(Collectors.toList());
}
kawasima
  • 1
  • 1
0

A PriorityQueue is good choice for this kind of requirement. To know more about PriorityQueue follow below link: How do I use a PriorityQueue?

One thing to note is that the PriorityQueue iterator does not provide the elements in order. you have to remove the elements to iterate over its elements in order.

Also you need to use reverse natural order of PriorityQueue using collections.reverseOrder. To know more about reversing natural order PriorityQueue follow below link: Reverse natural order using collections.reverseOrder()

Community
  • 1
  • 1
kamal
  • 84
  • 1
  • 6
0

Sort the array in either ascending or descending order and pick either the first or last item in the array depending on the order!

Collections.sort(arrayList); // Sort the arraylist
arrayList.get(arrayList.size() - 1); //gets the last item, largest for an ascending sort

More can be found here.

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161