Yakhoob
Yakhoob

Reputation: 569

Add list values to Treemap in actual order using Java

I have a list of map objects in the following manner

List<Map<String, Object>> insurancePercentageDetails = dao.getinusrancePercentageDetails(age);

This gives me the output in the following way.

[{Age=42, Rate12=0.40, Rate24=0.63, Rate36=0.86, Rate48=1.12, Rate60=1.39, Rate72=1.67, Rate84=1.98, Rate96=2.31, Rate108=3.30, Rate120=3.84, Rate132=4.40, Rate144=5.00, Rate156=5.62, Rate168=6.28, Rate180=6.97, Rate192=7.34, Rate204=7.74, Rate216=8.15, Rate228=8.07, Rate240=8.33}]

My actual target is to have a map in the following sorted order

{12=0.4,24=0.63 ....}

For this I took a static list

private final static List<String> period = new ArrayList<>
                    (Arrays.asList("Rate12","Rate24","Rate36","Rate48","Rate60","Rate72","Rate84","Rate96","Rate108","Rate120",
                            "Rate132","Rate144","Rate156","Rate168","Rate180","Rate192","Rate204","Rate216","Rate228","Rate240"));

Then

    TreeMap<String, Float> insuranceMatrixMap = new TreeMap<String, Float>();


for(String str : period) {  
            insuranceMatrixMap.put(str.replaceAll("Rate", ""), ((BigDecimal) (BBUtil.getInstance().getValue(insurancePercentageDetails, str))).floatValue());
        }

This gives me the output

{108=3.3, 12=0.4, 120=3.84, 132=4.4, 144=5.0, 156=5.62, 168=6.28, 180=6.97, 192=7.34, 204=7.74, 216=8.15, 228=8.07, 24=0.63, 240=8.33, 36=0.86, 48=1.12, 60=1.39, 72=1.67, 84=1.98, 96=2.31}

Not in sorted order.

TreeMap should keep the keys in the sorted order, Isn't it?

Am I missing anything here?

Upvotes: 0

Views: 872

Answers (2)

Vikram Rawat
Vikram Rawat

Reputation: 1662

You are right that TreeMap will sort based on the keys. But in your case the Key is String rather than Integer.

And the result is sorted based on the String Value, i.e. "108".compareTo("12") will be negative.

The String comparison is based on the Unicode value of each character. You have to use TreeMap<Integer, Float> if you want to sort on the Integer value.

Upvotes: 1

Amir Azizkhani
Amir Azizkhani

Reputation: 1804

you can sort it before loop same this :

Collections.sort(period, new Comparator<String>() {
            @Override
            public int compare(final String o1, final String o2) {
                return Integer.valueOf(o1.replaceAll("Rate", ""))
                        .compareTo(Integer.valueOf(o2.replaceAll("Rate", "")));
            }
        });

Upvotes: 0

Related Questions