0

I have a HashMap.

Map<String,String> lhm = new HashMap<String,String>();
lhm.put("Zara", "biu");
lhm.put("Mahnaz", "nuios");
lhm.put("Ayan", "sdfe");
lhm.put("Daisy", "dfdfh");
lhm.put("Qadir", "qwe");

I want to sort that hashmap according to the sequence which is given in properties file.Actually that property entry will be having the keys in some order.My property entry will looks like this

seq=Ayan,Zara,Mahnaz,Qadir,Daisy

What I have tried towards this is

Map<String,String> lhm = new HashMap<String,String>();
Properties prop=new Properties();
prop.load(new FileInputStream("D:\\vignesh\\sample.properties"));
// Put elements to the map
lhm.put("Zara", "biu");
lhm.put("Mahnaz", "nuios");
lhm.put("Ayan", "sdfe");
lhm.put("Daisy", "dfdfh");
lhm.put("Qadir", "qwe");

// Get a set of the entries
Set<Entry<String, String>> set = lhm.entrySet();
// Get an iterator
Iterator<Entry<String, String>> iter = set.iterator();
// Display elements
String sequence=prop.getProperty("seq");
System.out.println("sequence got here is "+sequence);
String[] resultSequence=sequence.split(",");

for(int j=0;j<resultSequence.length;j++)
{
   while(iter.hasNext()) {

     Map.Entry me = (Map.Entry)iter.next();
     String res=(String) me.getKey();

     if(res.equals(resultSequence[j]))
     {
       System.out.println("values according with the sequence is "+lhm.get(resultSequence[j]));
     }   
   }
}

The output which I'm getting after this is

sequence got here is Ayan,Zara,Mahnaz,Qadir,Daisy
values according with the sequence is sdfe

My expected output is

values according with the sequence is sdfe
values according with the sequence is biu
values according with the sequence is nuios
values according with the sequence is qwe
values according with the sequence is dfdfh

It is working for the first iteration in my for loop.After that it exits from my for loop also.What I'm missing here??Thanks for reading.

5
  • Check: String sequence=prop.getProperty("seq"); Are you certain it contains anything that can be splitted with a ","? Commented Sep 5, 2013 at 8:11
  • Yes.That entries are in comma seperated value. Commented Sep 5, 2013 at 8:14
  • I think i'm doing something wrong with my for loop Commented Sep 5, 2013 at 8:16
  • And how many values are there? If the for loop only runs once then resultSequence.length obviously is 1!! Commented Sep 5, 2013 at 8:17
  • Its not one.length is 5.Probably you should read my question again.Issue solved anyways thanks Commented Sep 5, 2013 at 8:19

9 Answers 9

5

It's not working because you never reset your iterator. You only match the string on your first run. Try putting the iterator inside the loop, to get a new one for every iteration, like this:

for(int j=0;j<resultSequence.length;j++)
{
     Iterator<Entry<String, String>> iter = set.iterator();
     while(iter.hasNext()) {
       ....
     }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I would not suggest this solution at all (Even in my dreams). Sorting a map, or any collection this way is literally abuse of the entire sorting algorithms available.
@RohitJain True, but this is the simplest way of achieving the current goal without major refactoring. And to improve bad code, it IS generally a good idea to start from the simple, stupid solution, then work your way toward better ones.
Agree. But you should suggest OP of better solutions in your answer, apart from solving the issue in his probably inefficient solution.
There's already plenty of other answers describing how to do that :)
3

You are complicating your task too much. In fact, you are just printing your values in sorted order, but not actually sorting them. Also, that's a pathetic way to implement sorting. You are iterating over your map as much number of times as there are strings in your sequence (Currently it's 5).

You should use a TreeMap instead, if you want to sort your keys. Here, you will need to pass custom Comparator, which will compare based on value in your property file.

Suppose you have order in a string:

String order = "Ayan,Zara,Mahnaz,Qadir,Daisy";

then your comparator would look like:

Comparator<String> comparator = new Comparator<String>() {
        @Override
        public int compare(String key1, String key2) {
            return order.indexOf(key1) - order.indexOf(key2);
        }
    };

The comparator compares each key in the TreeMap based on it's index in the order string. Now just pass this comparator to the overloaded TreeMap constructor.

SortedMap<String,String> lhm = new TreeMap<String,String>(comparator);

Now, whatever you insert in the map, will be sorted according to the order defined in property file.

To iterate over the map, you can use enhanced for loop:

for(Entry<String, String> entry : lhm.entrySet()) {
    System.out.println(entry.getValue());
}

6 Comments

When i'm iterating the map now,iter.next giving value like Ayan=sdfe..??
@VigneshVino. What do you want? If you just want the values, then you can iterate over the values.
You can use enhanced for loop rather to iterate over the entrySet() of the map. And get the value using entry.getValue(), for each entry.
In case If I need key means how can I get key?Iterating is giving value like I said above
@VigneshVino. Look at the Entry inner class of Map. It has two methods - getKey() and getValue().
|
1

You should get iterator for each iteration of for loop:

...

for(int j=0;j<resultSequence.length;j++)
{
    // Get an iterator
    Iterator<Entry<String, String>> iter = set.iterator();

    while(iter.hasNext()) {

...

Comments

1

Use a TreeMap. This allows you to write a custom comparator for sorting the entries.

Comments

0

HashMap does not save any order, I think you should use LinkedHashMap that iterates in same order that values were inserted.

1 Comment

I don't want that.I need to compare the values which i'm getting from hashmap and match those with my sequence from my property file enrty
0

I think that you don't need iterate with the while loop, once you get the ordered array with the keys from the properties file is enough to do this:

for (String key:resultSequence) {
    String value = lhm.get(key);
    System.out.println("values according with the sequence is "+ value); 
}

Comments

0

Iterate over the keys of your property file. For each of them, get the element in your map, if it exists.

Comments

0

Your while loop only get executed only once , because the iterator doesn't hold any more values after it reached the last element . Instead of while iterator use

for each loop Or else create a new iterator inside for loop and try

Comments

0

Well as the other answers have shown your error which is not reseting the iterator, let me propose another way of doing what you are trying to achieve.

If you want to go through the entire list, intead of using an iterator and writing the usual while(iter.hasNext()){} loop you may want to consider using a for loop as in the following example :

    Map<String,String> lhm = new HashMap<String,String>();
    // Put elements to the map
    lhm.put("Zara", "biu");
    lhm.put("Mahnaz", "nuios");
    lhm.put("Ayan", "sdfe");
    lhm.put("Daisy", "dfdfh");
    lhm.put("Qadir", "qwe");

    for(Entry<String, String> e : lhm.entrySet()) {
        // do something as the for loop iterates through your map.
        // e being the current element.
    }   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.