Java中的排序列表 [英] Sorted List in Java

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

问题描述

我需要按以下方式在Java中对列表进行排序:

I need to sort the list in java as below:

列表包含这样的对象的集合

List contains collection of objects like this,

List list1 = {obj1, obj2,obj3,.....};

我需要最终列表,该列表具有最低价值"和名称应避免重复".

I need the final list which has "lowest value" and "repetition of name should avoid".

例如:

List list1 = {[Nellai,10],[Gujarath,10],[Delhi,30],[Nellai,5],[Gujarath,15],[Delhi,20]}

排序后,我需要这样的列表:

After Sorting , I need the list like this :

List list1 = {[Nellai,5],[Gujarath,10],[Delhi,20]};

我的列表中有2个德里(30,20).但我只需要一个票价最低的德里(20).

I have 2 Delhi (30,20) in my list. But I need only one Delhi which has lowest fare (20).

如何在Java中做到这一点?

How to do that it in java?

Gnaniyar Zubair

Gnaniyar Zubair

推荐答案

与@Visage答案几乎相同,但是顺序不同:

Almost the same as @Visage answer, but the order is different:

public class NameFare {
    private String name;
    private int fare;
    public String getName() {
        return name;
    }
    public int getFare() {
        return fare;
    }
    @Override public void equals(Object o) {
        if (o == this) {
            return true;
        } else if (o != null) {
            if (getName() != null) {
                return getName().equals(o.getName());
            } else {
                return o.getName() == null;
            }
        }
        return false;
    }
}
....
public Collection<NameFare> sortAndMerge(Collection<NameFare> toSort) {
    ArrayList<NameFare> sorted = new ArrayList<NameFare>(toSort.size());
    for (NameFare nf : toSort) {
        int idx = sorted.getIndexOf(nf); 
        if (idx != -1) {
            NameFare old = sorted.get(idx);
            if (nf.getFare() < old.getFare()) {
                sorted.remove(idx);
                sorted.add(nf);
            }
        }
    }
    Collections.sort(sorted, new Comparator<NameFare>() {
        public int compare(NameFare o1, NameFare o2) {
            if (o1 == o2) {
                return 0;
            } else {
                if (o1.getName() != null) {
                    return o1.getName().compareTo(o2.getName()); 
                } else if (o2.getName() != null) {
                    return o2.getName().compareTo(o1.getName()); 
                } else {
                    return 0;
                }
            }
        }
    });
}

这篇关于Java中的排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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