D3KA
D3KA

Reputation: 37

How to keep the N highest values?

I'm doing a method that takes the value from a lot of objects with double getDelay(). But I need some help because I don't know how to save the 6 higher values. I thought to make a loop and save values in an array but I don't know how to insert a new value and delete the smallest and reordering the array. Any suggestions to save and order the values?

EDIT: Thanks to all, I forgot to say that I have to save the object (or the name in a String with getName(), I don't care) too. I thought use queues but I don't control them a lot. How can I order it? Because if I use Array.sort I don't know of what objects are this values

Upvotes: 0

Views: 1172

Answers (3)

AlexR
AlexR

Reputation: 2408

You'll actually want to create a Comparator<MyObject> and sort an array of MyObject directly:

Comparator<MyObject> myComparator = (o1, o2) -> {
    o1.getDelay() > o2.getDelay() ? -1 : (o1.getDelay() < o2.getDelay()  ? 1 : 0);
} // Reverse order by getDelay()
MyObject[] stuff;
Arrays.sort(stuff, myComparator);
for (int i = 0; i < 6; i++) {
    doSomething(stuff[i]);
}

Upvotes: 1

hitz
hitz

Reputation: 1110

You can add all values in an double[] array. Then use Arrays.sort() like this:

Arrays.sort(array,Collections.reverseOrder()); // this will sort array in descending order

Now you can access first 6 elements of this array to get largest 6 values.

EDIT: If you want to keep objects as well, you can use TreeMap<Double,Object>. Populate it with ids and objects. The elements in TreeMap are sorted by key which is Double here.

You can then retreive last 6 elements in TreeMap like this:

List<Object> highest = new ArrayList<Object>;  
for(int i=0; i<6; i++){
    Double last = treemap.getLastKey();
    Object objLast = treemap.get(last);
    hightest.put(objLast);
    treemap.remove(last);

}

Note: I have used ArrayList to store objects with highest double if you want to keep both you can instead use Map implementation to save both double and Object. Hope this helps.

Upvotes: 1

KDB
KDB

Reputation: 19

You can just use Arrays.sort(yourArr) and then take the last N entries.

See answer: Java - Ordering array values from highest to lowest

Upvotes: 1

Related Questions