Maruli Maruli - 1 month ago 9
Java Question

Retrieving KeySet from LinkedHashMap in specified order

I am writing a program which extracts keys from a

List of LinkedHashMap
. Extracted keys will then be concatenated with commas and printed as column headers in a CSV file.

Sample content of the
flatJson
looks like this:

{
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
}


Code:

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;
}


The order of headers I am getting from this program is:

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


While the expected output is the same as the
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


Previously, I were using
HashMap
and
Set
which don't support ordering. I have since changed them to
LinkedHashMap
and
TreeSet
but still can't get the right order.

Answer

A TreeSet is not about preserving insertion order. It is about sorting its elements.

In other words: if you add String objects to a TreeSet, they get ordered as if you would be sorting that list!

So, if order is your primary concern, you should use the LinkedHashSet instead of TreeSet! Alternatively, you could provide a custom Comparator upon creating your TreeSet ... that somehow gives you that order you are looking for - that might work, but smells like hackish workaround to me.