简体   繁体   English

Java-按关系分组排序

[英]Java - Sorting Grouped by Ties

I'm writing a Java program in which I want to sort a set of items and get the N-highest elements of the set. 我正在编写一个Java程序,其中要对一组项目进行排序并获得该组中N个最高的元素。 The thing is, though, that I want the elements to be returned grouped by their rank -- so if I want the 3 highest elements, but there is a tie between two elements for third place, then the third result is a collection that contains the two tied elements. 事实是,我希望按元素的排名将元素归还-因此,如果我希望获得3个最高的元素,但是两个元素之间有一个并列第三的位置,则第三个结果是包含以下内容的集合这两个绑在一起的元素。

I know I could write this myself, but I'm wondering if it's already been implemented somewhere else. 我知道我可以自己写这个,但是我想知道它是否已经在其他地方实现了。 Does anybody know of anything like this? 有人知道这样的事吗?

Sounds like the Google Collection's MultiMap might be what you're after. 听起来好像您在追求Google Collection的MultiMap

Use the "rank" as your key when inserting your elements. 插入元素时,请使用“等级”作为关键字。 Then sort the keys. 然后对键进行排序。

This is what I ended up going with: 这就是我最终要进行的工作:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.common.collect.Ordering;

public final class Sorting {
    private Sorting() {}

    public static <T extends Comparable<? super T>> List<List<T>> rank(
            Iterable<T> iterable, int nRanks) {
        if (nRanks < 0) {
            throw new IllegalArgumentException(Integer.toString(nRanks));
        }
        if (nRanks == 0) {
            return new ArrayList<List<T>>();
        }

        Iterator<T> iter = Ordering.natural().sortedCopy(iterable).iterator();
        List<List<T>> ret = new ArrayList<List<T>>();
        if (iter.hasNext()) {
            T prev = iter.next();
            List<T> group = new ArrayList<T>();
            group.add(prev);
            ret.add(group);

            int rank = 1;
            while (iter.hasNext()) {
                T next = iter.next();
                if (prev.compareTo(next) > 0) {
                    rank++;
                    if (rank > nRanks) {
                        break;
                    }

                    group = new ArrayList<T>();
                    ret.add(group);
                }
                group.add(next);
                prev = next;
            }
        }

        return ret;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM