使用三元组中的一个值对地图中的三元组列表进行排序

时间:2017-12-29 12:12:12

标签: java tuples

我有一个像这样的三元组的hashmap:

HashMap<String, List<Triplet<String,Integer,Integer>>> output = new HashMap<String, List<Triplet<String,Integer,Integer>>>();

如果密钥是文件名,则三元组包含单词及其频率信息(tf和df)的信息。例如

{File1 = {coffee,23,1},{caffeine,12,2},{brew,9,1}; File2 = {}.......}

我想根据三元组的第二个值(即术语频率)对这个三元组列表的值进行排序。

for (Entry<String, List<Triplet<String, Integer, Integer>>> entry : output.entrySet()) {
    String key = entry.getKey();
    List<Triplet<String, Integer, Integer>> value = entry.getValue();

接下来会发生什么?

以下是Triplet的样子:

public class Triplet<T, U, V> {

    private final T first;
    private final U second;
    private final V third;

    public Triplet(T first, U second, V third) {
        this.first = first;
        this.second = second;
        this.third = third;
    }

    public T getFirst() { 
        return first;
    }

    public U getSecond() { 
        return second; 
    }

    public V getThird() {
        return third; 
    }
}

任何帮助,指导将不胜感激。

3 个答案:

答案 0 :(得分:0)

我想到的方法有两种:

  1. 制作您的Triplet Comparable

  2. 撰写Comparator

  3. 您可以对列表进行排序或使用例如一个TreeSet

答案 1 :(得分:0)

如果您无法通过实施Triplet来更改Comparable课程,那么这将是一个使用Collections.sort方法的解决方案:

for (Entry<String, List<Triplet<String, Integer, Integer>>> entry : output.entrySet()) {
        String key = entry.getKey();
        List<Triplet<String, Integer, Integer>> value = entry.getValue();

        // This sorts the list using the anonymous instantiated Comparator class
        Collections.sort(value, new Comparator<Triplet<String, Integer, Integer>>(){
            @Override
            public int compare(Triplet<String, Integer, Integer> object1, Triplet<String, Integer, Integer> object2) {
                return object1.getSecond().compareTo(object2.getSecond());
            }
        });

或者,以更通用的方式,不使用硬类型:

Collections.sort(value, new Comparator<Triplet>(){
                @Override
                public int compare(Triplet object1, Triplet object2) {
                    return object1.getSecond().compareTo(object2.getSecond());
                }
            });

答案 2 :(得分:-1)

这个怎么样?

public class Triplet<T, U, V> implements Comparable<Triplet<T, U, V> > {

    private final T first;
    private final U second;
    private final V third;

    public Triplet(T first, U second, V third) {
        this.first = first;
        this.second = second;
        this.third = third;
    }

    public T getFirst() { 
        return first;
        }
    public U getSecond() { 
        return second; 
        }
    public V getThird() {
        return third; 
        }
    public int compareTo(Triplet<T, U, V> comparetrpl) {
        T a = comparetrpl.getFirst();
        //ascending order
        return (this.first > a) ? 1 : 0;

        //descending order
        //return (a > this.first) ? 1 : 0;

    }
}

使用sort方法?