【问题标题】:Sorting arrayList which has multiple fields对具有多个字段的arrayList进行排序
【发布时间】:2015-01-01 16:35:58
【问题描述】:

我有一个 Gift 类型的数组列表 每个 Present 对象都有字段 String name, String type , double Cost

我想找到一种使用每个礼物的成本对 arrayList 进行排序的方法

我使用的语言是 Java

请问我该怎么做

【问题讨论】:

标签: java sorting arraylist


【解决方案1】:

我想找到一种使用每个礼物的成本对 arrayList 进行排序的方法

您需要:

  1. 在您的自定义 Present 类中实现 Comparable
  2. 创建一个自定义 Comparator 以与 Collection.sort(...) 方法一起使用

这是我的例子,展示了这两种方法:

/*
**  Use the Collections API to sort a List for you.
**
**  When your class has a "natural" sort order you can implement
**  the Comparable interface.
**
**  You can use an alternate sort order when you implement
**  a Comparator for your class.
*/
import java.util.*;

public class Person implements Comparable<Person>
{
    String name;
    int age;

    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public String getName()
    {
        return name;
    }

    public int getAge()
    {
        return age;
    }

    public String toString()
    {
        return name + " : " + age;
    }

    /*
    **  Implement the natural order for this class
    */
    public int compareTo(Person p)
    {
        return getName().compareTo(p.getName());
    }

    static class AgeComparator implements Comparator<Person>
    {
        public int compare(Person p1, Person p2)
        {
            return p1.getAge() - p2.getAge();
        }
    }

    public static void main(String[] args)
    {
        List<Person> people = new ArrayList<Person>();
        people.add( new Person("Homer", 38) );
        people.add( new Person("Marge", 35) );
        people.add( new Person("Bart", 15) );
        people.add( new Person("Lisa", 13) );

        // Sort by natural order

        Collections.sort(people);
        System.out.println("Sort by Natural order");
        System.out.println("\t" + people);

        // Sort by reverse natural order

        Collections.sort(people, Collections.reverseOrder());
        System.out.println("Sort by reverse natural order");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by age

        Collections.sort(people, new Person.AgeComparator());
        System.out.println("Sort using Age Comparator");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by descending age

        Collections.sort(people, Collections.reverseOrder(new Person.AgeComparator()));
        System.out.println("Sort using Reverse Age Comparator");
        System.out.println("\t" + people);
    }
}

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      您可以使用Comparable or Comparator。在您的情况下,Comparable 更可取。

      【讨论】:

        猜你喜欢
        • 2016-04-15
        • 1970-01-01
        • 2022-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多