Java 如何使用多个排序条件对 ArrayList 进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3704804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:42:04  来源:igfitidea点击:

How to sort an ArrayList using multiple sorting criteria?

javacollectionsarraylistsorting

提问by Sheehan Alam

I have an array list that contains Quote objects. I want to be able to sort alphabetically by name, by change, and by percent change. How can I sort my arraylist?

我有一个包含 Quote 对象的数组列表。我希望能够按名称、变化和百分比变化按字母顺序排序。如何对我的数组列表进行排序?

package org.stocktwits.model;

import java.io.Serializable;
import java.text.DecimalFormat;

    public class Quote implements Serializable {

        private static final long serialVersionUID = 1L;

        public String symbol;
        public String name;
        public String change;
        public String percentChange;
        public String open;
        public String daysHigh;
        public String daysLow;
        public String dividendYield;
        public String volume;
        public String averageDailyVolume;
        public String peRatio;
        public String marketCapitalization;
        public String yearHigh;
        public String yearLow;
        public String lastTradePriceOnly;
        public DecimalFormat df = new DecimalFormat("#,###,###,###,###,##0.00");
        public DecimalFormat vf = new DecimalFormat("#,###,###,###,###,##0");

        public String getSymbol() {
            return symbol;
        }
        public void setSymbol(String symbol) {
            this.symbol = symbol;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getChange() {
            return change;
        }
        public void setChange(String change) {
            if(change.equals("null")){
                this.change = "N/A";
            }
            else{   
                float floatedChange = Float.valueOf(change);
                this.change = (df.format(floatedChange));
            }
        }
        public String getPercentChange() {
            return percentChange;
        }
        public void setPercentChange(String percentChange) {
            if(percentChange.equals("null"))
                percentChange = "N/A";
            else
                this.percentChange = percentChange;
        }
        public String getOpen() {
            return open;
        }
        public void setOpen(String open) {
            if(open.equals("null"))
                this.open = "N/A";
            else
                this.open = open;
        }
        public String getDaysHigh() {
            return daysHigh;
        }
        public void setDaysHigh(String daysHigh) {
            if(daysHigh.equals("null"))
                this.daysHigh = "N/A";
            else{
                float floatedDaysHigh = Float.valueOf(daysHigh);
                this.daysHigh = (df.format(floatedDaysHigh));
            }
        }
        public String getDaysLow() {
            return daysLow;
        }
        public void setDaysLow(String daysLow) {
            if(daysLow.equals("null"))
                this.daysLow = "N/A";
            else{
                float floatedDaysLow = Float.valueOf(daysLow);
                this.daysLow = (df.format(floatedDaysLow));
            }
        }
        public String getVolume() {
            return volume;
        }
        public void setVolume(String volume) {
            if(volume.equals("null")){
                this.volume = "N/A";
            }
            else{
                float floatedVolume = Float.valueOf(volume);
                this.volume = (vf.format(floatedVolume));
            }
        }
        public String getDividendYield() {
            return dividendYield;
        }
        public void setDividendYield(String dividendYield) {
            if(dividendYield.equals("null"))
                this.dividendYield = "N/A";
            else
                this.dividendYield = dividendYield;
        }
        public String getAverageDailyVolume() {
            return averageDailyVolume;
        }
        public void setAverageDailyVolume(String averageDailyVolume) {
            if(averageDailyVolume.equals("null")){
                this.averageDailyVolume = "N/A";
            }
            else{
                float floatedAverageDailyVolume = Float.valueOf(averageDailyVolume);
                this.averageDailyVolume = (vf.format(floatedAverageDailyVolume));
            }
        }
        public String getPeRatio() {
            return peRatio;
        }
        public void setPeRatio(String peRatio) {
            if(peRatio.equals("null"))
                this.peRatio = "N/A";
                else
            this.peRatio = peRatio;
        }
        public String getMarketCapitalization() {
            return marketCapitalization;
        }
        public void setMarketCapitalization(String marketCapitalization) {
            if(marketCapitalization.equals("null"))
                this.marketCapitalization = "N/A";
            else
                this.marketCapitalization = marketCapitalization;
        }
        public String getYearHigh() {
            return yearHigh;
        }
        public void setYearHigh(String yearHigh) {
            if(yearHigh.equals("null"))
                this.yearHigh = "N/A";
            else
                this.yearHigh = yearHigh;
        }
        public String getYearLow() {
            return yearLow;
        }
        public void setYearLow(String yearLow) {
            if(yearLow.equals("null"))
                this.yearLow = "N/A";
            else
                this.yearLow = yearLow;
        }

        public String getLastTradePriceOnly() {
            return lastTradePriceOnly;
        }

        public void setLastTradePriceOnly(String lastTradePriceOnly) {
            if(lastTradePriceOnly.equals("null")){
                this.lastTradePriceOnly = "N/A";
            }
            else{
                float floatedLastTradePriceOnly = Float.valueOf(lastTradePriceOnly);
                this.lastTradePriceOnly = (df.format(floatedLastTradePriceOnly));
            }
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((change == null) ? 0 : change.hashCode());
            result = prime * result
                    + ((daysHigh == null) ? 0 : daysHigh.hashCode());
            result = prime * result + ((daysLow == null) ? 0 : daysLow.hashCode());
            result = prime
                    * result
                    + ((lastTradePriceOnly == null) ? 0 : lastTradePriceOnly
                            .hashCode());
            result = prime
                    * result
                    + ((marketCapitalization == null) ? 0 : marketCapitalization
                            .hashCode());
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            result = prime * result + ((open == null) ? 0 : open.hashCode());
            result = prime * result + ((peRatio == null) ? 0 : peRatio.hashCode());
            result = prime * result
                    + ((percentChange == null) ? 0 : percentChange.hashCode());
            result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
            result = prime * result + ((volume == null) ? 0 : volume.hashCode());
            result = prime * result
                    + ((yearHigh == null) ? 0 : yearHigh.hashCode());
            result = prime * result + ((yearLow == null) ? 0 : yearLow.hashCode());
            return result;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Quote other = (Quote) obj;
            if (change == null) {
                if (other.change != null)
                    return false;
            } else if (!change.equals(other.change))
                return false;
            if (daysHigh == null) {
                if (other.daysHigh != null)
                    return false;
            } else if (!daysHigh.equals(other.daysHigh))
                return false;
            if (daysLow == null) {
                if (other.daysLow != null)
                    return false;
            } else if (!daysLow.equals(other.daysLow))
                return false;
            if (lastTradePriceOnly == null) {
                if (other.lastTradePriceOnly != null)
                    return false;
            } else if (!lastTradePriceOnly.equals(other.lastTradePriceOnly))
                return false;
            if (marketCapitalization == null) {
                if (other.marketCapitalization != null)
                    return false;
            } else if (!marketCapitalization.equals(other.marketCapitalization))
                return false;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            if (open == null) {
                if (other.open != null)
                    return false;
            } else if (!open.equals(other.open))
                return false;
            if (peRatio == null) {
                if (other.peRatio != null)
                    return false;
            } else if (!peRatio.equals(other.peRatio))
                return false;
            if (percentChange == null) {
                if (other.percentChange != null)
                    return false;
            } else if (!percentChange.equals(other.percentChange))
                return false;
            if (symbol == null) {
                if (other.symbol != null)
                    return false;
            } else if (!symbol.equals(other.symbol))
                return false;
            if (volume == null) {
                if (other.volume != null)
                    return false;
            } else if (!volume.equals(other.volume))
                return false;
            if (yearHigh == null) {
                if (other.yearHigh != null)
                    return false;
            } else if (!yearHigh.equals(other.yearHigh))
                return false;
            if (yearLow == null) {
                if (other.yearLow != null)
                    return false;
            } else if (!yearLow.equals(other.yearLow))
                return false;
            return true;
        }
    }

采纳答案by gpeche

Create an appropiate Comparatorthat will compare two items according to your desired criteria. Then use Collections.sort()on your ArrayList.

创建一个适当的Comparator,将根据您所需的标准比较两个项目。然后Collections.sort()在您的 ArrayList 上使用 。

If at a later time you want to sort by different criteria, call Collections.sort()again with a different Comparator.

如果稍后您想按不同的标准进行排序,请Collections.sort()使用不同的Comparator.

回答by Nikita Rybak

Sun has devoted big part of its tutorial to sorting in Java collections:
http://download.oracle.com/javase/tutorial/collections/interfaces/order.html

Sun 将其教程的很大一部分用于 Java 集合的排序:http:
//download.oracle.com/javase/tutorial/collections/interfaces/order.html

It discusses both Comparable and Comparator interfaces with examples.

它通过示例讨论了 Comparable 和 Comparator 接口。

回答by gpeche

See Collections.sortwith an explicit Comparator (or the Collections.sort kind that requires the input to implement Comparable, if you prefer).

Collections.sort有一个明确的比较(或Collections.sort那种需要输入来实现可比,如果你喜欢)。

回答by Peter Tillemans

If you (almost) always want to use that order you can add the Comparable interface to Quote and implement a compareTo method.

如果您(几乎)总是想使用该订单,您可以将 Comparable 接口添加到 Quote 并实现 compareTo 方法。

 public int compareTo(Quote quote) {
     int result = this.getName().compareTo(quote.getName());
     if (result == 0) {
        result = this.getChange().compareTo(quote.getChange());
     }
     if (result == 0) {
        result = this.getPercentChange().compareTo(quote.getPercentChange());
     }
     return result;
 }

Then use a sorted collection, or sort a list, and the quotes will be sorted.

然后使用已排序的集合,或对列表进行排序,引号将被排序。

For ad hoc sorting, a separate, possibly anonymous, Comparator is better.

对于临时排序,单独的,可能是匿名的,比较器更好。

回答by romacafe

Everybody is right that you want to use Comparators. Extending on that idea, if you want to be able to sort on multiple criteria, then a class like this will work for you:

每个人都想使用比较器是对的。扩展这个想法,如果您希望能够根据多个条件进行排序,那么这样的类将适合您:

public class MultiComparator<T> implements Comparator<T> {
    private List<Comparator<T>> comparators;

    public MultiComparator(List<Comparator<T>> comparators) {
        this.comparators = comparators;
    }

    public int compare(T o1, T o2) {
        for (Comparator<T> comparator : comparators) {
            int comparison = comparator.compare(o1, o2);
            if (comparison != 0) return comparison;
        }
        return 0;
    }
}

Then you just write really simple comparators for whichever fields you desire and you can combine them into more complex comparators more easily and with more reuse.

然后,您只需为您想要的任何字段编写非常简单的比较器,您就可以更轻松地将它们组合成更复杂的比较器,并具有更多的重用性。

回答by strangeoptics

Have a look at the ComparatorChain from the Apache Commons Collection. This should do the job. Don't implement logic if is already available and tested.
At the following site I have a tutorial: Sorting Objects By Multiple Attributes"

查看 Apache Commons Collection 中的 ComparatorChain。这应该可以完成工作。如果已经可用并经过测试,则不要实现逻辑。
在以下站点,我有一个教程:Sorting Objects By Multiple Attributes”

回答by sagar borse

There are two things:

有两件事:

  1. Sorting on multiple fields of an object
  2. Multilevel sorting (Here sorting done on first field and then next sorting applied on grouping done on similar items in previous sort)
  1. 对对象的多个字段进行排序
  2. 多级排序(这里对第一个字段进行排序,然后对上一个排序中的相似项目进行分组后应用下一个排序)

For #2: I found this below article very much close to what i desire http://strangeoptics.blogspot.com/2011/09/sorting-objects-by-multiple-attributes.html

对于 #2:我发现下面这篇文章非常接近我想要的 http://strangeoptics.blogspot.com/2011/09/sorting-objects-by-multiple-attributes.html