What is most efficient method to store 3 max values found in a hashmap ? (java) -


i have hash map containing objects, need write method returns 3 objects maximal value (calculated method), looking efficient data structure use.

what need data structure can hold 3 sorted values, , every time add value larger of elements pushes smallest value out , puts new value in proper index.

is there similar have describes or have create new object store data?

seems there no such thing in standard library.

but easy yourself! create array size of 4. add values it. once has 3 values , you're trying add 4th one, add fourth , sort list. time add value overwrite 4th 1 , sort again.

here short example script should give 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) {         (int = 0; < 10; i++) {             int newint = (int) (math.random() * 30);             system.out.println("adding " + newint);             addvalue(newint);             system.out.println(arrays.tostring(topthree));         }     } } 

results in 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] 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -