How to use SortedMap interface in Java?

前端 未结 6 625
谎友^
谎友^ 2020-12-01 02:03

I have a

 Map

What is the best way to keep the map sorted according to the float?

Is SortedMap

6条回答
  •  一个人的身影
    2020-12-01 02:15

    You can use TreeMap which internally implements the SortedMap below is the example

    Sorting by ascending ordering :

      Map ascsortedMAP = new TreeMap();
    
      ascsortedMAP.put(8f, "name8");
      ascsortedMAP.put(5f, "name5");
      ascsortedMAP.put(15f, "name15");
      ascsortedMAP.put(35f, "name35");
      ascsortedMAP.put(44f, "name44");
      ascsortedMAP.put(7f, "name7");
      ascsortedMAP.put(6f, "name6");
    
      for (Entry mapData : ascsortedMAP.entrySet()) {
        System.out.println("Key : " + mapData.getKey() + "Value : " + mapData.getValue());
      }
    

    Sorting by descending ordering :

    If you always want this create the map to use descending order in general, if you only need it once create a TreeMap with descending order and put all the data from the original map in.

      // Create the map and provide the comparator as a argument
      Map dscsortedMAP = new TreeMap(new Comparator() {
        @Override
        public int compare(Float o1, Float o2) {
          return o2.compareTo(o1);
        }
      });
      dscsortedMAP.putAll(ascsortedMAP);
    

    for further information about SortedMAP read http://examples.javacodegeeks.com/core-java/util/treemap/java-sorted-map-example/

提交回复
热议问题