简体   繁体   English

根据对象的字符串字段对ArrayList中的对象进行排序

[英]Sorting objects in an ArrayList based on their String field

guys! 伙计们! I am doing a coursework for uni and I am stuck on something. 我正在为uni进行课程学习,但遇到了一些困难。 I have a hierarchy of classes and an ArrayList in which objects from those classes are stored. 我有一个类的层次结构和一个ArrayList,其中存储了这些类的对象。 My code prints out objects' details stored in the ArrayList but I have to print them out according to a String field and I don't know how to do it. 我的代码打印出存储在ArrayList中的对象的详细信息,但是我必须根据String字段将其打印出来,但我不知道该怎么做。 I need to print the details according to the title field in LibraryItem class and it is specified that I need to use Java Class Libraries. 我需要根据LibraryItem类中的标题字段打印详细信息,并且指定需要使用Java类库。 I looked through some stuff and based on what I've seen I'm guessing I need to use Comparable but I have no idea how it works... Here are parts of the code: 我浏览了一些内容,并根据所看到的内容猜测是否需要使用Comparable,但我不知道它的工作原理……这是代码的一部分:

public class LibraryItem {

        private String title;
        private String itemCode;
        private int timesBorrowed;

...


public void printDetails()
        {
            System.out.println("\nTitle: " + title);
            System.out.println("Item code: " + itemCode);
            System.out.println("Cost: " + cost);
            System.out.println("Times borrowed: " + timesBorrowed);
            System.out.println("On loan: " + onLoan);
        }
}

... ...

public abstract class AudioVisual extends LibraryItem{

    private int playingTime;

    public AudioVisual()
    {
        super();
        playingTime = 80;
    }

public void printDetails()
    {
        super.printDetails();
        System.out.println("Playing time: " + playingTime);
    }

... ...

public class CD extends AudioVisual{

    private String artist;
    private int noOfTracks;

    public CD()
    {
        super();
        artist = "The Animals";
        noOfTracks = 9;
    }
public void printDetails()
{
    super.printDetails();
    System.out.println("Artist: " + artist);
    System.out.println("Number of tracks: " + noOfTracks);
}

... ...

public class DVD extends AudioVisual{

    private String director;

    public DVD()
    {
        director = "Director1";
    }
public void printDetails()
    {
        super.printDetails();
        System.out.println("Director: " + director);
    }

... ...

public class Library
{
    private ArrayList<LibraryItem> itemList;

    public Library()
    {
        itemList = new ArrayList<LibraryItem>();
    }

    public void printAllDetails()
    {
        for (LibraryItem item: itemList)
        {
            item.printDetails();
        }
    }

Again CD and DVD objects are added in the ArrayList. 再次将CD和DVD对象添加到ArrayList中。 Thank you in advance! 先感谢您!

There is an overload on Collections.sort that takes a Comparator , you can use it, Collections.sort上有一个需要Comparator的重载,您可以使用它,

 Collection.sort(items, new Comparator<LibraryItem>{
  @Override
  public int compare(LibraryItem a, LibraryItem b) {
    return a.title.compareTo(b.title);
  }
}

If you using Java 8, then there is a less verbose version using lambdas . 如果您使用的是Java 8,那么使用lambdas的版本就不那么冗长了。

Collections.sort(items,(item1,item2) -> item1.title.compareTo(item2.title));

You can do it in two ways: 您可以通过两种方式进行操作:

  1. Use Comparable interface which would be implemented by LibraryItems class by implementing compareTo method. 使用Comparable接口,该接口将由LibraryItems类通过实现compareTo方法来实现。
  2. Use Comparator interface which would be a seperate class and implement compare method. 使用Comparator接口(将是一个单独的类)并实现compare方法。

Whichever way you choose, your implementation would be something like: 无论选择哪种方式,您的实现都将如下所示:

public int compare(LibraryItem item1, LibraryItem item2) {//if you are implementing Comparator
     return item1.getTitle().compareTo(item2.getTitle());//if you want to sort item by title
}

And then before printing the list, you could sort them like: 然后在打印列表之前,可以对它们进行排序:

Collections.sort(itemList, <comparator object>);//if using comparator or you could omit passing comparator object.
//iterate and print items

Streams way (the original collection untouched) 流方式(原始收藏未触及)

    itemList.stream()
            .sorted(Comparator.comparing(LibraryItem::getTitle))
            .forEachOrdered(LibraryItem::printDetails);

Collection sort in place (ie with side effects) 收集到位(即有副作用)

    Collections.sort(itemList, Comparator.comparing(LibraryItem::getTitle));
    for (LibraryItem item : itemList) {
        item.printDetails();
    }

employees.stream().collect(Collectors.summingInt(Employee::getSalary))); employee.stream()。collect(Collectors.summingInt(Employee :: getSalary)));

here employees indicate the list. 在这里,员工指出清单。 You can replace summingInt with group by or something similar, Employee is the class name and getSalary is the property on which you need to sort. 您可以用group by或类似的替代替换summingInt,Employee是类名,getSalary是需要排序的属性。

for further reference you can browse through 为了进一步参考,您可以浏览

http://download.java.net/lambda/b88/docs/api/java/util/stream/Collectors.html http://download.java.net/lambda/b88/docs/api/java/util/stream/Collectors.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM