Java - Sort one array based on values of another array?

后端 未结 10 1819
不思量自难忘°
不思量自难忘° 2020-11-30 12:02

I have an array of Strings that are instances of a class from external code that I would rather not change.

I also have an array of ints that was generated by callin

10条回答
  •  无人及你
    2020-11-30 12:32

    package com.appkart.array;
    
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.TreeMap;
    
    public class SortExample {
    
        Map map = new HashMap();
        Map treemap = new TreeMap(
                new MyComparator(map));
    
        public void addValueInMapAndSort() {
            map.put("string1", 40);
            map.put("string2", 32);
            map.put("string3", 34);
    
            System.out.println(map);
            treemap.putAll(map);
            System.out.println(treemap);
        }
    
    
        class MyComparator implements Comparator {
    
            Map map;
    
            public MyComparator(Map map) {
                this.map = map;
            }
    
            @Override
            public int compare(String o1, String o2) {
                if (map.get(o1) >= map.get(o2)) {
                    return 1;
                } else {
                    return -1;
                }
            }
        }
    
        public static void main(String[] args) {
            SortExample example = new SortExample();
            example.addValueInMapAndSort();
        }
    }
    

    Use Comparator for sorting according to value.

提交回复
热议问题