【问题标题】:Sorting in Collections [duplicate]在集合中排序[重复]
【发布时间】:2012-08-21 16:13:52
【问题描述】:

可能重复:
Can I sort two lists in relation to each other?

我有一个排序方案,我不知道如何实现它? 两个集合

List<<String>String> Key, List<<String>String> Value 我必须从 a-z 对值进行排序,这样对应值的键不应该改变。

>>eg: Key and Value  
    2=>two  
    100=>four  
    1=>five  
    0=>nine  
    3=>eight  
    8=>one

>>after Sorting:
    3=>eight  
    1=>five  
    100=>four  
    0=>nine
    8=>one
    2=>two

有人请帮帮我吗?

【问题讨论】:

  • 并且排序后不按字母顺序排序... 8=>one, 0=>nine ?
  • 我的列表是分开的。不在一个集合中。即键和值或在与索引匹配的单独集合中。我必须对值进行排序,以便重新排序键。

标签: java sorting data-structures collections


【解决方案1】:

使用以文本为键的树形图(“二”、“四”),我们可以按字母顺序排序,然后再次检索这两个列表:

// Key contains ("2", "100", "1", ...)
// Value contains ("two", "four", "five", ...)
SortedMap<String, String> result = new TreeMap<String, String>();

// assuming the same size for both lists
for (int i = 0; i < Key.size(); i++) {
    // when adding to TreeMap, keys are ordered automatically
    result.put(Value.get(i), Key.get(i));
}

List<String> orderedKey = new ArrayList<String>(result.keySet());
List<String> orderedValue = new ArrayList<String>(result.values());

希望这会有所帮助。

【讨论】:

    【解决方案2】:
    【解决方案3】:

    使用 TreeMap 怎么样?您有两个对应条目的元组,您可以根据需要对它们进行排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 2019-07-05
      • 1970-01-01
      • 2019-10-29
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多