2017-11-26 11 views
0

を使用して、実際のために、ツリーマップに追加私はこれが私に次のように出力を提供しますは、リストの値は、Java

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

、次のようにマップオブジェクトのリストを持っています。

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

私の実際のターゲットは、私は、静的リスト次に

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")); 

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


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

これを取り、次のソート順このため

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

にマップを持つことです私に出力を与える

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

ソート順ではありません。

TreeMapは、キーをソート順に保持する必要がありますか?

ここに何か不足していますか?

+1

ソートされた順序ですが、数値の順序ではなく***文字列の照合値に従います。数値順にソートする場合は、キーを「整数」に変更するか、正しい順序付けを行うカスタムコンパレータを用意する必要があります。 –

+0

@ジムガリソン、そうです。 TreeMap insuranceMatrixMapをTreeMap insuranceMatrixMapに変更しました。それを答えに入れてください。私は受け入れるでしょう – Yakhoob

答えて

0

あなたは、ループの前に、この同じそれを並べ替えることができます。

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", ""))); 
      } 
     }); 
+0

ジムの答えを確認してください。その解決策で十分です。あなたの返信ありがとう – Yakhoob

1

あなたはTreeMapのは、キーに基づいて並べ替えられますことを右です。 あなたのケースでは、KeyはIntegerではなくStringです。

結果は文字列値に基づいてソートされます。つまり、 "108" .compareTo( "12")は負の値になります。

文字列の比較は、各文字のUnicode値に基づいています。 Integer値をソートする場合は、TreeMap<Integer, Float>を使用する必要があります。

+0

うん。正しい.. – Yakhoob

関連する問題