我有以下 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()));
}
}
这是我的第一个问题,所以我深表歉意并感谢大家的耐心等待。
最佳答案
您可以使用简单的比较器和流来实现此目的:
entrySet.stream().sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey())).collect(Collectors.toList());
显然,如果您只想迭代它,则不必收集它。 (如果键相等,您可能还想使用该值进行比较,尽管您的问题中没有提到这一点。)
我假设集合和键中都没有空值。
编辑:感谢 @JornVernee 指出 Map#Entry
已经有一个 Comparator
。使用它,它看起来像这样(如果您只想迭代它们,collect
仍然是可选的;您也可以使用稍微不同的语法为键指定不同的比较器):
entrySet.stream().sorted(Entry.comparingByKey(/*Comparator<String> if needed*/))
.collect(Collectors.toList());
关于Java - 如何对 Set<Entry<K,V>> 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38209357/