java - 使用 Comparable 对 ArrayList 进行排序

标签 java sorting arraylist

尝试使用 Comparable,我是编程新手,从未对 ArrayList 进行过排序。我看过一些关于堆栈溢出的其他示例并查看了 Java Doc,但它相当困惑,我不确定如何将它应用到我的程序中

基本上我有两个类,一个 Personality 类和一个 PersonalityList 类。 PersonalityList类包含一个名为personalities的Personality数组,ArrayList中存储了无数的personality对象。

我需要根据每个人物的得票数对其进行排序。方法 top(int topValue) 应该返回一个长度为 topValue 的新数组,其中包含投票最高的 Personality 对象。

我知道我需要在我的 Personality 类中使​​用一些 Comparable,但不确定如何执行此操作。

到目前为止,这是我的 PersonalityList 类:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Collections;

public class PersonalityList
{
    private ArrayList<Personality> personalities; //Create ArrayList of Personality, called personalities.
    private ArrayList<Personality> sortedPersonalities;

    /**
     * Constructor for objects of class PersonalityList
     */
    public PersonalityList()
    {
      personalities = new ArrayList<Personality>(); //Initialise personalities ArrayList.
      sortedPersonalities = new ArrayList<Personality>();
    }

    /**
     * Adds a personality to the ArrayList of Personality, called personalities. 
     */
    public void addPersonality(Personality personality)
    {
       personalities.add(personality);
    }

    /**
     * Returns the number of Personality objects in the ArrayList
     */
    public int getSize()
    {
       return personalities.size(); 
    }

    /**
     * Lists the details of all the Personality objects stored in the ArrayList
     */
    public void list()
    {
       System.out.println("Personality List");

       for(Personality personality : personalities) { //Iterates through each personality in ArrayList
           System.out.println(personality.getDetails()); 
       }

       System.out.println();
    }

     /**
     * Adds one vote to the personality which matches the name entered into the method
     */
    public void voteFor(String name)
    {
         boolean nameFound = false; //Boolean variable to identify if the personality has been found
         int index = 0;

         while (index < personalities.size() && !nameFound) {
             Personality personality = personalities.get(index);
             String compName = personality.getName();

             if (compName.equals(name)) { //Adds a vote if the name is found
                 personality.increaseVotes(1);
                 nameFound = true;
             } 

             index++;
         }

         if (nameFound == false) { //Error message if name not found
             System.out.println(name + " could not be found.");
         }
    }

    /**
     * Removes personalities if they have less votes than the parameter value
     */
    public void shortlist(int minimumVotes) 
    {
        Iterator<Personality> it = personalities.iterator();

        while(it.hasNext()) {
            Personality personality = it.next();
            int currentP = personality.getVotes();

            if (currentP < minimumVotes) { 
                 it.remove();
            }
        }
    }



    /**
     * 
     */
    public Personality top(int topValue)
    {
        int index = 0;
        int listSize = personalities.size();

        if (topValue > listSize) {
            topValue = listSize;
        }

        if(listSize > 0) {

            //Coppies the ArrayList personalities to the sortedPersonalities ArrayList
            while(index < topValue) {
                Personality sortedPersonality = personalities.get(index);
                sortedPersonalities.add(sortedPersonality);
                System.out.println(sortedPersonality.getDetails());
                index++;
            }

            Collections.sort(sortedPersonalities, Collections.reverseOrder(new Personality.votesComparator()));
            System.out.println("Sorted by Votes");
            System.out.println("\t" + people);
        } 
        else {
            System.out.println("No personalities are currently in the Array List");
        }

        return sortedPersonalities ;
    }
}

提前致谢。

最佳答案

或者您可以使用如下 lambda 表达式轻松地执行对象之间的比较:

假设我们有一个 Person 及其年龄的列表;

       List<Person> peopleList =new ArrayList<Person>();
        peopleList.add(new Person("Ann", 23));
        peopleList.add(new Person("Sam", 22));
        peopleList.add(new Person("John", 20));
        peopleList.add(new Person("Watson", 23));
        peopleList.add(new Person("Samuels", 31));
        peopleList.add(new Person("Peter",41));
        peopleList.add(new Person("Harry", 28));
        peopleList.add(new Person("Carter", 19));
        peopleList.add(new Person("Lilly", 26));
        peopleList.add(new Person("Kumar", 12));
        peopleList.add(new Person("Insaf", 51));

我们可以使用Comparator界面比较这些人的年龄

Comparator<Person> personComparatorByAgeUsingStream =(Person b1,Person b2)->{return ((Integer)b1.getAge()).compareTo((Integer)b2.getAge());};   

然后我们可以将这些人排序到一个列表中:

List<Person> streamSort= peopleList
                        .stream()
            .sorted(personComparatorByAgeUsingStream).collect(Collectors.toList());

 streamSort.forEach(x->{System.out.println(x.getName()+" is "+x.getAge()+" years old.");});

关于java - 使用 Comparable 对 ArrayList 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33860496/

相关文章:

algorithm - 插入排序中比较和交换的区别

algorithm - 有效的函数排序

java - 查找ArrayList中出现次数最多的字符串

java - 如何创建一个填充不同类型对象的 ArrayList?

java - 如何从 String 中提取尾随零的数量

java - 将可变大小的数组从 C 返回到 Java

java - 等待一个线程以.join不一致结束

java - euler 项目 #10 无法在 java 上得到答案

java - 使用 Java Collat​​or 区分大小写的顺序

java - 表达式的类型必须是数组类型,但它被解析为 ArrayList<Point2D.Double>