2

我有一个Map<Reference, Double>挑战的实例是键对象可能包含对同一对象的引用,我需要返回相同类型的“输入”映射,但按属性键分组并保留最大值。

我尝试使用groupingBymaxBy但我被卡住了。

private void run () {
    Map<Reference, Double> vote = new HashMap<>();

    Student s1 = new Student(12L);
    vote.put(new Reference(s1), 66.5);
    vote.put(new Reference(s1), 71.71);
    Student s2 = new Student(44L);
    vote.put(new Reference(s2), 59.75);
    vote.put(new Reference(s2), 64.00);

    // I need to have a Collection of Reference objs related to the max value of the "vote" map
    Collection<Reference> maxVote = vote.entrySet().stream().collect(groupingBy(Map.Entry.<Reference, Double>comparingByKey(new Comparator<Reference>() {
        @Override
        public int compare(Reference r1, Reference r2) {
            return r1.getObjId().compareTo(r2.getObjId());
        }
    }), maxBy(Comparator.comparingDouble(Map.Entry::getValue))));
}

class Reference {
    private final Student student;

    public Reference(Student s) {
        this.student = s;
    }
    public Long getObjId() {
        return this.student.getId();
    }
}

class Student {
    private final  Long id;
    public Student (Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }
}

maxBy我的论点有一个错误:Comparator.comparingDouble(Map.Entry::getValue)我不知道如何解决它。有没有办法达到预期的结果?

4

2 回答 2

1

您可以使用Collectors.toMap来获取集合Map.Entry<Reference, Double>

Collection<Map.Entry<Reference, Double>> result = vote.entrySet().stream()
        .collect(Collectors.toMap( a -> a.getKey().getObjId(), Function.identity(),
            BinaryOperator.maxBy(Comparator.comparingDouble(Map.Entry::getValue)))).values();

然后再次流过以获得List<Reference>

List<Reference> result = vote.entrySet().stream()
        .collect(Collectors.toMap(a -> a.getKey().getObjId(), Function.identity(),
            BinaryOperator.maxBy(Comparator.comparingDouble(Map.Entry::getValue))))
        .values().stream().map(e -> e.getKey()).collect(Collectors.toList());
于 2020-05-26T09:49:02.327 回答
0

使用groupingByand的方法maxBy

Comparator<Entry<Reference, Double>> c = Comparator.comparing(e -> e.getValue());

        Map<Object, Optional<Entry<Reference, Double>>> map = 
                           vote.entrySet().stream()
                           .collect(
                            Collectors.groupingBy
                            (
                            e -> ((Reference) e.getKey()).getObjId(),                             
                            Collectors.maxBy(c)));

           // iterate to get the result (or invoke another stream)
        for (Entry<Object, Optional<Entry<Reference, Double>>> obj : map.entrySet()) {
            System.out.println("Student Id:" + obj.getKey() + ", " + "Max Vote:" + obj.getValue().get().getValue());
        }

输出(用于您问题的输入):

Student Id:12, Max Vote:71.71
Student Id:44, Max Vote:64.0
于 2020-05-26T10:17:14.393 回答