Sorting a hash map
I have a hashmap with strings as keys, and float values as values, like below:
{"anne=0.23453, barry=1.254339,steven=0.12449... }
what i want to do is sort this hashmap according to the float values, returning the highest float value first. What i am currently doing is, swapping the keys with the values, so that the floats are the keys, and sorting them with a hashmap:
Set set = map1.keySet();
Map invertedMap = new HashMap();
for(Object o : set)
float val = (Float)map1.get(o);
invertedMap.put(val, o);
TreeMap sorted = new TreeMap(Collections.reverseOrder());
sorted.putAll(map1);
Set set1 = sorted.keySet();
Iterator it = set1.iterator();
while(it.hasNext()) {
Object o = it.next();
System.out.println( o + " " + map1.get(o));
}The problem here is that in the hash tables there a few floats are the same value, ie henry=1.6743, and mary=1.6743
so when i invert the hash table, making 1.6743 one of these is ignored. Can anbody think of a way i can do this?
Id appreciate any help
Thanks
Thanks, ive stored the entrySet in a list. A little
unsure how to go about writting comparator to sort
them by value though. Would you be able to explain
this in a little more detail, please?Write a class that implements java.util.Comparator. Thre's but one method to implement, that is
public int compare(Object o1, Object o2);
Expect the arguments to be keys in your map. Fetch the value for each key and compare the values. That should be a problem since, if I got it right, those are java.lang.Floats, which implement java.lang.Comparable, so you can simply return: value1.compareTo(value2).
Take a minute or two to read the Javadoc of the Comparator's compare method.
Similar Messages
-
How to disable sorting in hash map
im adding like this ,
Map Params = new HashMap();
params.put("orderYear", "1");
params.put("distrChannel", "2");
params.put("salesOffice", "3");
while iterating answer is coming like this
1
3
2
but i want
1
2
3
thanks in advance
gowriwhile iterating answer is coming like this
1
3
2You can print the Sorted HashMap values using the following way:
HashMap map = new HashMap();
map.put("1","First");
map.put("2","Second");
map.put("3","Third");
ArrayList keys = new ArrayList();
keys.addAll(map.keySet());
Collections.sort(keys);
Iterator it = keys.iterator();
while (it.hasNext())
System.out.println(it.next());
Refer the outcome keys, and print the HashMap values, thats all. -
Hi All ,
I i have the data in below format:
Name Age Skill Company
Vass 21 Java Zylog
Samy 24 PB HP
Lee 18 ADF CTS
Reng 16 Java Info
I converted this data into java collections List<Hash Map> like this.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class HashMapDemo {
public static void main(String[] args) {
// Create a hash map
List<HashMap> list = new ArrayList<HashMap>();
HashMap hm = new HashMap();
hm.put("Name", new String("Vass"));
hm.put("Age", new Integer(21));
hm.put("Company", new String("Zylog"));
hm.put("skill", new String("Java"));
list.add(hm);
HashMap hm1 = new HashMap();
hm1.put("Name", new String("Samy"));
hm1.put("Age", new Integer(24));
hm1.put("Company", new String("HP"));
hm1.put("skill", new String("PB"));
list.add(hm1);
HashMap hm2 = new HashMap();
hm2.put("Name", new String("Lee"));
hm2.put("Age", new Integer(18));
hm2.put("Company", new String("CTS"));
hm2.put("skill", new String("ADF"));
list.add(hm2);
HashMap hm3 = new HashMap();
hm3.put("Name", new String("Reng"));
hm3.put("Age", new Integer(16));
hm3.put("Company", new String("Info"));
hm3.put("skill", new String("Java"));
list.add(hm3);
Iterator i = list.iterator();
while (i.hasNext()) {
System.out.println(i.next());
} As per data (table format) i want to sort the data in Column level
how can i to achieve ?.
List<HashMap> is type of collection is help to me?
Any idea?
Thanks,
Vass LeeCheck out Comparator, and use Google to find examples on how to use it.
http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html
Still sorting a collection of hashmaps is a bit odd design though. I think you want to create a simple class with properties in stead of a HashMap, then implement Comparable on that class. -
Hi,
[b] how to sort hash map contains integer objects,
HashMap map=new HashMap();
map.put("1",new Integer("1"));
map.put("2",new Ineger("2")):
map.put("3",new Ineger("3")):
map.put(4,new Integer("4"));
map.put("10",new Integer("10"));
map.put("11",new Integer("11"));
map.put("12",new Integer("12"));
map.put("20",new Integer("20"));
map.put(30,new Integer("30"));
if i am using treemap
TreeMap map1=new TreeMap(map);
System.out.println(map1);
answer is
1 ,10,11,12,2,20,3,30,4
but i am accepting the results
1,2,3,4,10,11,12,20,30.
what to do
with regardsshannu sarma[/b]This is usual behaviour of a Map. You cannot sort a Set or Map. You can sort a List only using Collections.sort().
If you want to use a Map which adds all elements according to the order you've added it, then use LinkedHashMap.
And if you want to capture the keys, use Map.values() which returns an ordered Collection (and after converting it to List, you can sort it).
Another approach is to create a wrapper object and put it in a List. Then you can use the java.util.Comparator to sort objects in a List. -
Is it possible to insert a value in a hash map at a perticular index ?
Hello Techies,
I have a drop down list which is used to select a contry name. I also contains " All " option which is used to select all countries.
I am using HashMap for this drop down list for getting corresponding value.
Now, my requirement is the " All " should display as the first in the drop down list. Hash map didn't support bcoz it is in sorted order,
Can any one help me with alternative solution ?
Thanks in advance.
JavedNow, my requirement is the " All " should display as the first in the drop down
list. Hash map didn't support bcoz it is in sorted order,Rather HashMap doesn't support this because according to the first paragraph
of its API documentation "This class makes no guarantees as to the order of the
map; in particular, it does not guarantee that the order will remain constant over
time".
Is the drop down list a JComboBox? If so how are you using the hash map?
And can't you just create an array from the hash map's keys, putting "All" at the
start? -
Hi
Just a quick one
I have two hash maps - each containing information on the location of characters in a individual string.
Is there some sort of method that allows me to compare the two maps and return the string locations where they contain the same information ?Hi evett,
You might want to check out the method "entrySet()" in the Map class, once you get the 2 Set's, you can then use the "retainAll()" method of a Set to only keep the information that is the same in both Set's (which contains the information you want).
Good Luck,
Bud -
DTW Sort Error - after mapping during import
I got the "Sort Error - after mapping during import" message in DTW. (version 8.8)
I would like to import warehouse info for items.
My itemcodes are fix 15 character numbers, like this: 10204150020011
The note nr. [1331130|http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/oss_notes/sdn_oss_sbo_dtw/~form/handler%7b5f4150503d3030323030363832353030303030303031393732265f4556454e543d444953504c4159265f4e4e554d3d31333331313330%7d] said that I can't use recordkey like this.
Do you have any idea how can I import thees information with DTW?
Thank you,
Attila SarkadyDear All
Please give correct and complete information
i have tested every kind of combination;
- recreate the template with the dtw for Items = i have UDF's
- ADD the column RecordKey !!! unbelievable that we have to do this
- i have entered a nr 1 in it (even when we had already 850 items in the database)
(and of course the hints of Gordon - columns as text, start with basic... - and use CSV format)
now at last i can import the record line
greetings
philippe -
How to store double variable in hash map
i need to store double variable using hash map, but i cant able to store it
my jsp coding contains
double et=24,j=5;
hm.put("stm",st);
hm.put("etm",et);
Generated servlet error
C:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\exam\org\apache\jsp\availability_jsp.java:752:
put(java.lang.Object,java.lang.Object) in java.util.Map cannot be applied to (java.lang.String,double)
hm.put("stm",st);
^
how to overcome this problem
thank u in advancedouble etme;
etme = hm.getDouble("etm");
i'm getting this error
C:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\exam\org\apache\jsp\editdel_jsp.java:85: cannot resolve symbol
symbol : method getDouble (java.lang.String)
location: interface java.util.Map
etme = hm.getDouble("etm");
^
how to solve it
plz help me -
How to find Regular Expressions in a Hash Map
Hi,
I Have a hash map with some keys. The Keys are like this(Java.util.regex, Javax.swing.table, javax.swing.text, Java.util.jar, Java.text etc). Suppose if the user gives the search pattern as "text", the o/p should be javax.swing.text and java.text.. How to do it using regular Expressions// Sample code...
import java.util.regex.*;
public class TestRegex {
public static void main(String[] args) {
String test1 = "java.util.regex";
String test2 = "javax.swing.text";
String test3 = "java.util.jar";
String test4 = "java.text";
Pattern pat = Pattern.compile(".*text.*");
Matcher mt1 = pat.matcher(test1);
System.out.println("1> " +mt1.matches());
Matcher mt2 = pat.matcher(test2);
System.out.println("2> " +mt2.matches());
Matcher mt3 = pat.matcher(test3);
System.out.println("3> " +mt3.matches());
Matcher mt4 = pat.matcher(test4);
System.out.println("4> " +mt4.matches());
} -
Passing a Hash Map in a Custom Workflow.
I have a workflow WF_CUSTOM_TXT which inputs credentials such as resource name, type, connection string and then I am passing the attributes as a Hash Map: -
Map attributes =new HashMap();
attributes.put("firstname", "Nakul");
attributes.put("lastname", "Sharma");
When I launch the process in the java code which should pass the Hash Map for the workflow WF_CUSTOM_TXT, but i am unable to do so as I declared the attribute in the wrkflow which can be defined as a String. So mismatch occurs????
Another question that I have is that is it possible for us to pass a set of Multi values attributes as a Hash to a workflow and receive the same and then extract individual elements out of the hash toallocate to variables in the WF. Please provide any suggestions!!!!!!!!can you plz share the code, so that i can get what are you doing and where you stuck.
and also try to initialize the variable with hashmap objcet and the see -
hi,
I tried creating an array of hash maps in my application .
but it continued to give me problem
can any of u help me in this regard.
thank youint SIZE=...;
HashMap[] maps=new HashMap[SIZE];
for(int i=0; i<maps.length; i++){
maps=new HashMap();
Gil
Or, for a purposely misleading solution...int SIZE=...;
HashMap[] maps = new HashMap[SIZE];
java.util.Arrays.fill(maps, new HashMap()); -
Is there any linked hash map in flex??
Hi
Is there any linked hash map in flex??
Actually I am getting linked hash map from java but the objects inside them are scattered.
Thanks and Regards
Aruna.S.N.See the bottom of this LiveDoc page on ActionScript and Java type conversions.
http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_4.html
If this post answers your question or helps, please mark it as such. -
How to create a dicitionary using hash map.
Hi All,
I want to create a dictionary using hash map where in i can add new words and there meaning. I have written some code But I am not happy with this. Can you suggest me how to add the words and there meanings to the hash map.
I am not able to add the words and there meaning to the hash map.
for this i tried creating a dictionary class.
// Using hashmap
import java.util.*;
public class Dictionary
public static void main(String[] args)
// Create a hash map
HashMap hm = new HashMap();
// put elements to the map
hm.put("Abode: ", "Home");
hm.put("Balance: ", "An intrument to measure or weigh");
hm.put("Car: ", "Automobile");
hm.put("Dinner: ","Last meal of the day generally had after evening and before sleeping");
hm.put("Embossed: ", "Engraved kind");
Set set = hm.entrySet();
Iterator i = set.iterator();
while (i.hasNext())
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
System.out.println();
}This is the other Dictionary class which i created.
public class Main_Dictionary
public static void main(String[] args)
Content_Dictionary cd = new Content_Dictionary();
cd.getContent_Dictionary("Abode", "Home");
cd.displayValues();
class Content_Dictionary
String word, meaning;
Content_Dictionary()
word = "a";
meaning = "b";
Content_Dictionary(String x, String y)
word = x;
meaning = y;
void getContent_Dictionary(String w, String m)
word = w;
meaning = m;
void displayValues()
System.out.print(word + ": ");
System.out.println(meaning);
}If i create an interface containing all the words and there meaning
public interface Words_Dictionary
String Abode = "Home";
String Dark = "Lacking brightness";
String Balance = "An intrument to measure or weigh";
String Car = "Type of Automobile";
String Dinner = "Last meal of the day";
String Embossed = "Engraved kind";
String Adroit = "SkillFul";
}and then create a another class which implements this interface, but how should i add these words and there meaning in the hashmap.I tried creating word document but i was unable to
figure out how to do the operations on the word
document and its content,
So This is what i could come up with, i just created
one class Dictionary , now I am able to search for
the meaning of the word specified by me, and I am
able to print all the words and there meanings added
to the hashmap, but i am not able to figure out how
to add a new word and the meaning in the hashmap and
how to find is a word is there or not...May I suggest a slightly different approach?
Do not create a String ==> String mapping, but a String ==> List<String> mapping. And do NOT place everything inside your main method.
Here's a small demo:
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
public class Dictionary {
private Map< String, List<String >> dictionary;
public Dictionary() {
dictionary = new HashMap< String, List<String >>();
public void addWord(String base, String meaning) {
List<String> allMeanings = dictionary.get(base);
if(allMeanings == null) { // if null, there is no entry mapped to 'base' yet: create a new one
List<String> newMeanings = new ArrayList<String>();
newMeanings.add(meaning);
dictionary.put(base, newMeanings);
} else {
allMeanings.add(meaning);
public List<String> search(String base) {
// your code here
return null;
// ... other methods ...
public String toString() {
StringBuilder strb = new StringBuilder();
for(Map.Entry< String, List<String >> e : dictionary.entrySet()) {
strb.append(e.getKey());
strb.append(" : ");
strb.append(e.getValue());
strb.append('\n');
return strb.toString();
public static void main(String[] args) {
Dictionary dict = new Dictionary();
dict.addWord("Abode", "Home");
dict.addWord("Abode", "House");
dict.addWord("Car", "Automobile");
dict.addWord("Car", "Vehicle");
System.out.println(dict);
}Good luck. -
My while loop doesnt seem to work in a hash map, it works fine when I loop an array list.
It compiles but it doesnt seem to find any employees, should I use another loop?
{code
public Employee find(String id)
Employee foundEmployee = null;
int index = 0;
boolean found = false;
while(index < register.size() && !found){
Employee right = register.get(index);
String namn = right.getName();
if (namn.equals(id)){
foundEmployee = right;
found = true;
index++;
return foundEmployee;
what if you looped on the key set?
public Employee find(String id)
Employee foundEmployee = null;
Set<Integer> keySet = register.keySet();
for (Integer key : keySet)
Employee right = register.get(key);
if (right.getName().equals(id))
foundEmployee = right;
break;
return foundEmployee;
}
what if you looped on the key set?
public Employee find(String id)
Employee foundEmployee = null;
Set<Integer> keySet = register.keySet();
for (Integer key : keySet)
Employee right = register.get(key);
if (right.getName().equals(id))
foundEmployee = right;
break;
return foundEmployee;
}
What is the difference between standard,sorted and hash table
<b>can anyone say what is the difference between standard,sorted and hash tabl</b>
Hi,
Standard Tables:
Standard tables have a linear index. You can access them using either the index or the key. If you use the key, the response time is in linear relationship to the number of table entries. The key of a standard table is always non-unique, and you may not include any specification for the uniqueness in the table definition.
This table type is particularly appropriate if you want to address individual table entries using the index. This is the quickest way to access table entries. To fill a standard table, append lines using the (APPEND) statement. You should read, modify and delete lines by referring to the index (INDEX option with the relevant ABAP command). The response time for accessing a standard table is in linear relation to the number of table entries. If you need to use key access, standard tables are appropriate if you can fill and process the table in separate steps. For example, you can fill a standard table by appending records and then sort it. If you then use key access with the binary search option (BINARY), the response time is in logarithmic relation to
the number of table entries.
Sorted Tables:
Sorted tables are always saved correctly sorted by key. They also have a linear key, and, like standard tables, you can access them using either the table index or the key. When you use the key, the response time is in logarithmic relationship to the number of table entries, since the system uses a binary search. The key of a sorted table can be either unique, or non-unique, and you must specify either UNIQUE or NON-UNIQUE in the table definition. Standard tables and sorted tables both belong to the generic group index tables.
This table type is particularly suitable if you want the table to be sorted while you are still adding entries to it. You fill the table using the (INSERT) statement, according to the sort sequence defined in the table key. Table entries that do not fit are recognised before they are inserted. The response time for access using the key is in logarithmic relation to the number of
table entries, since the system automatically uses a binary search. Sorted tables are appropriate for partially sequential processing in a LOOP, as long as the WHERE condition contains the beginning of the table key.
Hashed Tables:
Hashes tables have no internal linear index. You can only access hashed tables by specifying the key. The response time is constant, regardless of the number of table entries, since the search uses a hash algorithm. The key of a hashed table must be unique, and you must specify UNIQUE in the table definition.
This table type is particularly suitable if you want mainly to use key access for table entries. You cannot access hashed tables using the index. When you use key access, the response time remains constant, regardless of the number of table entries. As with database tables, the key of a hashed table is always unique. Hashed tables are therefore a useful way of constructing and
using internal tables that are similar to database tables.
Regards,
Ferry Lianto
Maybe you are looking for
-
How to clear the vendors open documents pls give me advice
-
Transactions created by user "WEBLOGIN"
Hi Experts, We have ISA b2b ecom application. Very rarely, Order created by some user ID is replaced as created by WEBLOGIN. As per my understanding WEBLOGIN is the system user id no one will use the WEBLOGIN ID to create the orders. H
-
I have a series of PNG images (character and background) rendered out of Autodesk Maya (with Mental Ray) for compositing in AE. They are the DiffuseNoShadow, Indirect, and Shadow pass. Premultiply was disabled. I imported the sequences into AE, initi
-
Hello, everybody. I want to ask if there is a possibility to execute CDMC analysis (ABAP objects analysis) during transporting request in CCMS from QAS system to PRD.
-
I suddenly started getting hard disk error from a fictitious recovery software how do i get rid
I suddenly started getting hard disk error on my compaq laptop and some software called file recovery start running scans showing all sorts of errors and hiding all my files. I've lost all my icons can't see any files in explorer and upon looking int