gpt4 book ai didi

java - 按指定顺序从 LinkedHashMap 中检索 KeySet

转载 作者:行者123 更新时间:2023-11-30 08:31:49 26 4
gpt4 key购买 nike

我正在编写一个从 LinkedHashMap 列表 中提取键的程序。然后提取的键将用逗号连接起来,并打印为 CSV 文件中的列标题。

flatJson 的示例内容如下所示:

{
Submitted_Date=03-11-2016 01:19:41,
Comments=,
Rating=3,
details.name=Willy,
details.personalId=S123456A,
details.mobileNo=11111111,
details.email=willy@email.com,
Channel=desktop,
Referral_Code=,
discount.promoCode=,
discount.referral=,
policyPlan.grossPremium=788.64,
policyPlan.name=Standard,
policyPlan.netPremium=788.64
}

代码:

private TreeSet<String> collectHeaders(List<LinkedHashMap<String, String>> flatJson) {
TreeSet<String> headers = new TreeSet<String>();
for (LinkedHashMap<String, String> linkedMap : flatJson) {
headers.addAll(linkedMap.keySet());
}
return headers;
}

我从这个程序中得到的标题顺序是:

Channel
Comments
Rating
Referral_Code
Submitted_Date
details.email
details.personalId
details.mobileNo
details.name
discount.promoCode
discount.referral
policyPlan.grossPremium
policyPlan.name
policyPlan.netPremium

虽然预期的输出与 flatJson 相同:

Submitted_Date
Comments
Rating
details.name
details.personalId
details.mobileNo
details.email
Channel
Referral_code
discount.promoCode
discount.referral
policyPlan.grossPremium
policyPlan.name
policyPlan.netPremium

以前,我使用的是 HashMapSet,它们不支持排序。我已将它们更改为 LinkedHashMapTreeSet 但仍然无法获得正确的顺序。

最佳答案

TreeSet 与保留插入 顺序无关。它是关于排序它的元素。

换句话说:如果您将 String 对象添加到 TreeSet,它们将排序,就像您要排序该列表一样!

因此,如果订单 是您最关心的问题,您应该使用 LinkedHashSet而不是树集!或者,您可以提供自定义 Comparator在创建您的 TreeSet 时......以某种方式为您提供了您正在寻找的顺序 - 这可能有效,但对我来说闻起来像是 hackish 解决方法。

关于java - 按指定顺序从 LinkedHashMap 中检索 KeySet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40458757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com