0

I am having a Map and converting to charsequence[] by using the

final CharSequence[] treatmentNameList = treatmentListMap.keySet().toArray(new CharSequence[treatmentListMap.size()]);

but the value at position of charsequence[0] and map 0 is not is getting varied. how to get same values in both charsequence and map. i tried this also

final CharSequence[] treatmentNameList = treatmentListMap.keySet().toArray(new CharSequence[0]);

3 Answers3

1

You're getting a key Set. A set does not in general guarantee any order, hence the order being different for different calls. You may have more luck with a LinkedHashMap, if you are able to control the implementation of the map you're using. See the Javadocs for more information about them.

This post:

Does Java's LinkedHashMap maintain the order of keys?

has more information for you.

Community
  • 1
  • 1
user1111284
  • 886
  • 1
  • 6
  • 23
1

As suggested by user1111284, it perfectly works. Please look into the below code

public class MapToCharSequenceTest {

public static void main(String[] args){
    LinkedHashMap<String,String> contents = new LinkedHashMap<String,String>();

    contents.put("brass","rod");
    contents.put("Silver","spoon");
    contents.put("gold","ring");
    contents.put("iron","plate");
    Set<String> set = contents.keySet();
    final CharSequence[] charsequence  = set.toArray( new CharSequence[contents.size()]);
    for(CharSequence c : charsequence){
        System.out.println(c);
    }
}

}

0

Please read the javadoc for CharSequence. Have you seen http://docs.oracle.com/javase/6/docs/api/java/lang/CharSequence.html?