java关键字map,如何通过Java中的关键字对Map值进行排序

I have a Map in java that has strings for both .

Data is like following: , , ,

I want to sort the map based on its keys. So In the end I will have question1, question2, question3....an so on.

Eventually I am trying to get two strings out of this Map. First String: Questions ( in order 1 ..10) and Second String: Answers (in same order as question).

Right now I have the following:

Iterator it = paramMap.entrySet().iterator();

while (it.hasNext()) {

Map.Entry pairs = (Map.Entry)it.next();

questionAnswers += pairs.getKey()+",";

}

This gets me the questions in a string but they are not in order...

解决方案

Short answer

Use a TreeMap. This is precisely what its for.

If this map is passed to you and you cannot determine the type, then you can do the following:

SortedSet keys = new TreeSet(map.keySet());

for (String key : keys) {

String value = map.get(key);

// do something

}

This will iterate across the map in natural order of the keys.

Longer answer

Technically, you can use anything that implements SortedMap, but except for rare cases this amounts to TreeMap, just as using a Map implementation typically amounts to HashMap.

For cases where your keys are a complex type that doesn't implement Comparable or you don't want to use the natural order then TreeMap and TreeSet have additional constructors that let you pass in a Comparator:

// placed inline for the demonstration, but doesn't have to be an anonymous class

Comparator comparator = new Comparator() {

public int compare(Foo o1, Foo o2) {

...

}

}

SortedSet keys = new TreeSet(comparator);

keys.addAll(map.keySet());

Remember when using a TreeMap or TreeSet that it will have different performance characteristics than HashMap or HashSet. Roughly speaking operations that find or insert an element will go from O(1) to O(Log(N)).

In a HashMap, moving from 1000 items to 10,000 doesn't really affect your time to lookup an element, but for a TreeMap the lookup time will be about 3 times slower (assuming Log2). Moving from 1000 to 100,000 will be about 6 times slower for every element lookup.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值