【问题标题】:Java - How to sort a Set<Entry<K,V>>?Java - 如何对 Set<Entry<K,V>> 进行排序?
【发布时间】:2016-11-07 15:22:09
【问题描述】:

我有以下 Set,有一个 json 字符串。

Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();

我想让这个列表按键排序,但我被困在这里。您会建议一种排序方式,还是使用 JSON 的更好方式?

我的目的:

for(Entry entry : entrySet) {
  if( !"sign".equals(entry.getKey()) ){         
    JsonElement elemValue = jsonObject.get((String) entry.getKey());
    postParameters.add(new BasicNameValuePair((String) entry.getKey(), elemValue.getAsString()));
  } 
}

这是我的第一个问题,所以我很抱歉并感谢大家的耐心等待。

【问题讨论】:

  • 这些条目是否来自某种地图?如果是这样,您可以将其设为 TreeMap 并自动获取按键值排序的条目。
  • @csharpfolk 我想知道如果你不分配ComparatorEntry 将如何排序。
  • @KeqiangLi 你是对的,我删除了我的评论
  • @MickMnemonic 是 Google 的库的 JsonObject,Gson: public final class JsonObject extends JsonElement { private final LinkedTreeMap members = new LinkedTreeMap(); [...] public Set> entrySet() { return members.entrySet(); } [...] }

标签: java json sorting set key


【解决方案1】:

您可以使用简单的比较器和流来实现此目的:

    entrySet.stream().sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey())).collect(Collectors.toList());

显然,如果您只想迭代它,则不必收集它。 (如果键相等,您可能还想使用该值进行比较,尽管您的问题中没有提到这一点。)

我假设你在集合和键中都没有空值。

编辑:感谢@JornVernee 指出Map#Entrys 已经有一个Comparator。使用它,它看起来像这样(collect 仍然是可选的,以防您只想遍历它们;您也可以使用稍微不同的语法为键指定不同的比较器):

    entrySet.stream().sorted(Entry.comparingByKey(/*Comparator<String> if needed*/))
            .collect(Collectors.toList());

【讨论】:

  • 提示:您可以使用Map.Entry.comparingByKey()作为比较器。
  • 成功了!谢谢!我想出了一种在 For 之后对 postParameters 进行排序的方法,这也是一个很好的解决方案。 Collections.sort(postParameters, new Comparator&lt;NameValuePair&gt;() { @Override public int compare(NameValuePair o1, NameValuePair o2) { return(o1.getName().compareTo(o2.getName())); } });
  • 如果key是整数类型,比较器Comparator.comparingInt(e -&gt; Integer.parseInt(e.getKey()))可以用来保持基于整数值的顺序
猜你喜欢
  • 2012-08-26
  • 2021-04-06
  • 2011-04-21
  • 1970-01-01
  • 2019-05-03
  • 2012-03-31
  • 2013-04-13
  • 1970-01-01
相关资源
最近更新 更多