如何在Java中简洁的实现“装饰和排序”?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (53)

有以下代码:

origList = <something>
decorated = sorted( [(evalFunc(item), item) for item in origList] )
finalList = [item for _, item in decorated]

通过选择不同的evalFunc可以选择如何排序

class Note {
   ...
}
class Fitness {
    double goodness;
    double badness;
}

需要访问注释以外的几个数据

class Composition {
    ... data declared here ... ;

    public Fitness evaluate(Note n) {
    }
}

想比较一下Fitness按数字顺序排列的对象

class CompareFitnessByGoodness implements Comparator<Fitness> {
}

class CompareFitnessByBadness implements Comparator<Fitness> {
}

class Together {
    public Note;
    public Fitness;
}

整理一下List<Together>

class CompareTogetherByGoodness implements Comparator<Together> {
    ...
}

class CompareTogetherByBadness implements Comparator<Together> {
   ...
}

最后输入:

Note pickBest(List<Together> notes) {
    // Pick a note that's not too bad, and pretty good at the same 
    // time.

    // First sort in order of increasing badness, so I can choose
    // the bottom half for the next stage (i.e. the half "least bad"
    // notes).
    Collections.sort(notes, new CompareTogetherByBadness());
    List<Together> leastBadHalf = notes.subList(0, notes.size()/2);

    // Now sort `leastBadHalf` and take the last note: the one with
    // highest goodness.
    Collections.sort(leastBadHalf, new CompareTogetherByGoodness());

    return leastBadHalf.get(leastBadHalf.size()-1);
}
提问于
用户回答回答于
origList = <something>
decorated = sorted( [(evalFunc(item), item) for item in origList] )
finalList = [item for _, item in decorated]

Composition composer = ...;

List<Note> notes = ...;

List<Together> notesAllTogetherNow = notes.stream()
                                          .map(note -> new Together(note, composer.evaluate(note)))
                                          .sorted(new CompareTogetherByGoodness())
                                          .collect(Collectors.toList());
Optional<Note> bestNote = notes.stream()
                               .map(note -> new Together(note, composer.evaluate(note)))
                               .sorted(new CompareTogetherByBadness())
                               .limit(notes.size() / 2) // Taking the top half
                               .sorted(new CompareTogetherByGoodness())
                               .findFirst() // Assuming the last comparator sorts in descending order
                               .map(Together::getNote);
用户回答回答于

Java显然包括一个Collections.sort :: List -> Comparator -> List,不过Java的标准库不包括元组

扫码关注云+社区

领取腾讯云代金券