有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将lambda作为方法arg和排序映射传递


我必须创建排序方法,用映射参数和lambda表达式调用。该方法返回作为第一个参数传递的任何映射的排序版本,排序顺序由作为第二个参数给出的lambda表达式确定。 我创建了这样的东西(不能正常工作):

public Map sorted(Map map, Function<Set> funct){


    System.out.println(map.entrySet()
       .stream()
       .sorted((Comparator) funct)
       .collect(Collectors.toList()));
     return null;
}

有什么想法吗
谢谢你的帮助;)


共 (3) 个答案

  1. # 1 楼答案

    如果您想要一个排序映射,它将是一个TreeMap,并且假设比较器按Key排序,它可以如下所示:

     public static <K, V> TreeMap<K, V> sorted(Map<K, V> map, Comparator<? super K> cmp) {
    
        return map.entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey,     
                              Map.Entry::getValue, 
                              (left, right) -> left, 
                              () -> new TreeMap<K, V>(cmp)));
    
    }
    

    对它的调用如下所示,例如:

     System.out.println(sorted(map, Comparator.naturalOrder()));
    
  2. # 2 楼答案

    如果您想将ToIntBiFunction引用到Comparator,您可以使用以下方法:

    void sortByEntry() {
        Map<?, ?> map = new HashMap<>();
        Map<?, ?> sorted = sorted(map, this::comparingEntry);
    }
    
    <K, V> Map<K, V> sorted(Map<K, V> map, 
                            ToIntBiFunction<Entry<K, V>, Entry<K, V>> comparator) {
        return map.entrySet().stream()
                .sorted(comparator::applyAsInt)
                .collect(Collectors.toMap(Entry::getKey, Entry::getValue
                                        , (v1, v2) -> v2, LinkedHashMap::new));
    }
    
    <K, V> int comparingEntry(Entry<K, V> left, Entry<K, V> right) {
        return ...;
    }
    
  3. # 3 楼答案

    当我读到这个问题时,我想到了一个更一般的解决方案,在这个解决方案中,您可以根据键或值对地图进行排序。在这种情况下,解决方案如下所示:

    public static <K,V> Map<K,V> sorted(Map<K,V> map, Comparator<Map.Entry<K, V>> comparator){
        return map.entrySet()
           .stream()
           .sorted(comparator)
           .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
    }
    

    如果要按值排序,可以使用以下方法:

    sorted(yourMap, Entry.comparingByValue());