简体   繁体   中英

Sorting objects in an ArrayList based on their String field

guys! I am doing a coursework for uni and I am stuck on something. I have a hierarchy of classes and an ArrayList in which objects from those classes are stored. 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. 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. 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:

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. Thank you in advance!

There is an overload on Collections.sort that takes a Comparator , you can use it,

 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 .

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.
  2. Use Comparator interface which would be a seperate class and implement compare method.

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)));

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.

for further reference you can browse through

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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