replace duplicate values in hashmap java -
i have hashmap contains student id key , string value.
map<integer, string> data = new hashmap<integer, string>();
it contains data
1 2 b 3 4 c 5 b 6
i want find duplicate values in map , replace them integer values. i.e. want map like
1 1 2 2 3 1 4 3 5 2 6 1
i.e. map shud pick first value(a), find keys value , replace value of keys 1. pick second value(b) find keys , replace them 2 , on. file reading large cannot replace keys manually specifying each key. so, have tried far is
map<integer,integer> finalmap = new hashmap<integer,integer>(); int a=0; list mapkey = new arraylist(data.keyset()); list mapval = new arraylist(data.values()); iterator valit = mapval.iterator(); while(valit.hasnext()){ a=a+1; object valuet = valit.next(); iterator keyit = mapkey.iterator(); while(keyit.hasnext()){ object keyt = keyit.next(); string comp1 = data.get(keyt).tostring(); string comp2 = valuet.tostring(); if(comp1.equals(comp2)){ finalmap.put((string)keyt,a); } } }
but not giving me correct output. doesnt start a=1. think first calculates incremented values of a. have text file 1000 records. , output is
1 1000 2 987 3 1000 4 298 5 987 6 1000
i dont know m wrong. please me regarding this. thank you
first thing need understand, there no such thing "first" value in hashmap
. if want ordered base on key, should use treemap
instead.
if ordering not concern you, , need same integer replace same value, there lots of way do. 1 way (code not accurate, should demonstrate idea):
// setup map of oldvalue newvalue hashmap<string, integer> valuemap = ...; int = 0; (string oldvalue : data.values()) { if ( ! valuemap.contains(oldvalue )) { valuemap.put(oldvalue, ++i); } } // replace in data (map.entry<integer, string> dataentry : data.entryset()) { finalmap.put(dataentry.getkey(), valuemap.get(dataentry.getvalue()); }
Comments
Post a Comment