基于其中一个字段对元组进行排序

时间:2011-04-17 00:08:06

标签: java algorithm sorting

我的问题与下面的问题相同,但答案非常模糊,我不明白如何处理它。 sort a List<Tuple> from highest to lowest 如果你能更详细地描述如何做到这一点,将不胜感激。感谢

2 个答案:

答案 0 :(得分:7)

尝试运行我为您制作的这个示例并思考发生了什么:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Tuple<R, S, T>
{

private R name;
private S data;
private T index;

public Tuple(R r, S s, T t)
{
    this.name = r;
    this.data = s;
    this.index = t;
}

public static void main(String[] args)
{
    List<Tuple<String, int[], Integer>> tuples = new ArrayList<Tuple<String, int[], Integer>>();
    // insert elements in no special order
    tuples.add(new Tuple<String, int[], Integer>("Joe", new int[] { 1 }, 2));
    tuples.add(new Tuple<String, int[], Integer>("May", new int[] { 1 }, 1));
    tuples.add(new Tuple<String, int[], Integer>("Phil", new int[] { 1 }, 3));

    Comparator<Tuple<String, int[], Integer>> comparator = new Comparator<Tuple<String, int[], Integer>>()
    {

        public int compare(Tuple<String, int[], Integer> tupleA,
                Tuple<String, int[], Integer> tupleB)
        {
            return tupleA.getIndex().compareTo(tupleB.getIndex());
        }

    };

    Collections.sort(tuples, comparator);

    for (Tuple<String, int[], Integer> tuple : tuples)
    {
        System.out.println(tuple.getName() + " -> " + tuple.getIndex());
    }

}

public R getName()
{
    return name;
}

public void setName(R name)
{
    this.name = name;
}

public S getData()
{
    return data;
}

public void setData(S data)
{
    this.data = data;
}

public T getIndex()
{
    return index;
}

public void setIndex(T index)
{
    this.index = index;
}

}

答案 1 :(得分:0)

一般的答案只不过是那里给出的答案。要对列表进行排序,您需要让列表元素具有规范排序(即实现Comparable接口),或者让比较器对排序算法进行比较。然后,您可以使用Collections.sort来完成实际工作。