java - sorted map implementation (ValueComparableMap), sorting not maintained when calling Map.Entry setValue -


i've used solution here describes how implement value comparable map in java, , working fine put method, however, when try modify values in map through map.entry type, sorting no longer maintained. following code exhibits issue:

treemap<integer, float> valcompmap = new valuecomparablemap<integer, float>(ordering.natural()); // code puts entries in map random random = new random(); (map.entry<integer, float> e : valcompmap.entryset()) {   e.setvalue(e.getvalue() + random.nextfloat()); } //parse keys list list<integer> sorted_keys = new arraylist<integer>(valcompmap.keyset()); //here sorted_keys not sorted according values in original key value pair in map 

as work around, i'm re-putting keys new values such:

list<integer> keys = new arraylist<integer>(valcompmap.keyset()); (integer k : keys) {   valcompmap.put(k, valcompmap.get(k) + random.nextfloat()); } 

problems work around:

  1. not straight forward (doesn't express intent clearly)
  2. seem in-efficient since looking @ put method in valuecomparablemap, involves branching, searching, removing , 2x putting.

so efficient way modify value in such valuecomparablemap (while maintaining live sort property)?

here simple test demonstrate issue:

treemap<integer, float> valcompmap = new valuecomparablemap<integer, float>(ordering.natural());  //populate map random stuff random random = new random(); (int = 0; < 10; ++i) {   valcompmap.put(i, random.nextfloat()); }  //print system.out.println("before modifying, map:"); (map.entry<integer, float> e : valcompmap.entryset()) {   system.out.println(e.tostring()); }  //modify values in map (map.entry<integer, float> e : valcompmap.entryset()) {   e.setvalue(e.getvalue() + random.nextfloat()); }  //print system.out.println("after modifying, map:"); (map.entry<integer, float> e : valcompmap.entryset()) {   system.out.println(e.tostring()); }  //modify values in work-around way list<integer> keys = new arraylist<integer>(valcompmap.keyset()); (integer k : keys) {   valcompmap.put(k, valcompmap.get(k) + random.nextfloat()); }  //print system.out.println("after modifying using work-around, map:"); (map.entry<integer, float> e : valcompmap.entryset()) {   system.out.println(e.tostring()); } 

and here output:

before modifying, map: 6=0.05478877 4=0.07464349 1=0.08668131 2=0.0869472 3=0.32622492 8=0.35595274 5=0.3879655 9=0.602066 7=0.7913183 0=0.8479772  after medifying, map: 6=0.9277618 4=0.9426463 1=0.269701 2=0.95250356 3=0.8576952 8=0.547724 5=1.1656129 9=1.3945209 7=1.0475534 0=0.91609937  after modifying using work-around, map: 3=0.96215 6=1.036502 4=1.1082084 1=1.1496286 8=1.2940607 7=1.343531 0=1.4778173 2=1.6039091 5=1.6165544 9=2.1403322 


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -