将一个对象与另一个对象排序 [英] Sort an object by an other one

查看:114
本文介绍了将一个对象与另一个对象排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是交易:

我的应用程序中有发布对象. 我也有投票对象(forOrAgainst,author,linkedPublication)

I have Publication objets in my application. I also have Vote objet (forOrAgainst,author,linkedPublication)

我想按日期,标题...以及投票数对出版物进行排序.

I want to sort publication by date, title... and also by number of votes.

我无法直接对出版物列表进行排序,因为我在该列表中没有投票数. 如何在不向发布对象添加方法的情况下对发布列表进行排序.

I cant directly sort my list of publication as i dont have the number of vote in that list. How can i sort my list of publication without adding method to the publication object.

链接它们的最佳方法是什么?

What is the best way to link them ?

我应该返回一个哈希图吗?一个树丛?数组?

Should i return a hashmap ? a treeset ? an array ?

现在我的大脑有点混乱...

It's kinda messy in my brain now...

推荐答案

以下是使用

Here's an example of using Comparator to sort based on an external criteria:

import java.util.*;

class VoteComparator implements Comparator<String> {
    final Map<String, Integer> tally;
    VoteComparator(Map<String, Integer> tally) {
        this.tally = tally;
    }
    @Override public int compare(String pub1, String pub2) {
        int v1 = tally.get(pub1);
        int v2 = tally.get(pub2);
        return
           (v1 < v2) ? -1 :
           (v1 > v2) ? +1 :
           0;
    }           
};

为了简单起见,这里仅使用String进行发布;您想在应用程序中对Publication进行排序.这也使用一个简单的int来获取投票计数,但是从本质上讲,必须有一个提示服务,在给定Publication的情况下为您提供其Vote计数是多少.

This uses just String for publication for simplicity; you'd want to sort Publication in your application. This also uses a simple int to get the vote count, but essentially there has to be a tally service that gives you, given a Publication, what its Vote count is.

注意:英语不是我的母语,所以"tally"可能不是最合适的词,但基本上是某种投票登记员,投票记录员,本质上是一个对象之间的映射,以及它获得多少票

Note: English is not my first language, so perhaps "tally" isn't the right word for it, but basically some sort of vote registrar, vote recorder, essentially a map between an object, and how many votes it gets.

然后您可以使用TreeSet进行排序.

Then you can sort, using, say, TreeSet.

public class SortExample {
    public static void main(String[] args) {
        Map<String, Integer> tally = new HashMap<String, Integer>();
        tally.put("foo", 42);
        tally.put("bar", 13);
        tally.put("Fizz", 3);
        tally.put("Buzz", 5);
        tally.put("FizzBuzz", 15);

        Comparator<String> voteComparator = new VoteComparator(tally);
        SortedSet<String> sortedByVote = new TreeSet<String>(voteComparator);
        sortedByVote.addAll(tally.keySet());
        for (String pub: sortedByVote) {
            System.out.println(pub + " (" + tally.get(pub) + " votes)");
        }
    }
}

此打印:

Fizz (3 votes)
Buzz (5 votes)
bar (13 votes)
FizzBuzz (15 votes)
foo (42 votes)

这篇关于将一个对象与另一个对象排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆