-1

I have a hash map containing objects, I need to write a method which returns the 3 objects with a certain maximal value (calculated by another method), I am looking for the most efficient data structure to use.

what I need is a data structure that can hold 3 sorted values, and every time I add a value that is larger than any of its elements it pushes the smallest value out and puts the new value in its proper index.

Is there something similar to what I have describes or would I have to create a new object to store this data?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Ethan
  • 221
  • 5
  • 15
  • I don't think that exists, but you could use a `TreeMap` which will sort the `Integer`s as they are being added. – Josh M Aug 24 '13 at 04:49

1 Answers1

0

Seems like there is no such thing in the standard library.

But it is very easy to do yourself! You just create an array with the size of 4. Then add values to it. Once it has 3 values and you're trying to add a 4th one, add it as fourth and sort your list. Now any time you add another value simply overwrite the 4th one and sort again.

Here is a very short example script that should give you the idea:

import java.util.Arrays;

public class TempTest {

    static int[] topThree = new int[4];

    static public void addValue(int newVal) {
        if (newVal > topThree[0]) {
            topThree[0] = newVal;
            Arrays.sort(topThree);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            int newInt = (int) (Math.random() * 30);
            System.out.println("Adding " + newInt);
            addValue(newInt);
            System.out.println(Arrays.toString(topThree));
        }
    }
}

Results in this output:

Adding 23
[0, 0, 0, 23]
Adding 16
[0, 0, 16, 23]
Adding 2
[0, 2, 16, 23]
Adding 8
[2, 8, 16, 23]
Adding 28
[8, 16, 23, 28]
Adding 12
[12, 16, 23, 28]
Adding 0
[12, 16, 23, 28]
Adding 29
[16, 23, 28, 29]
Adding 6
[16, 23, 28, 29]
Adding 5
[16, 23, 28, 29]