0

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!

8
  • 1
    So you want to sort your List<LibraryItem> by title? Collections.sort(Comparator.comparing(LibraryItem::getTitle())). Commented Apr 19, 2015 at 10:49
  • Since the arrayList is in the Library class i'm guessing that I need to sort it there. But when I write down the piece of code you've suggested I get two errors. 1st LibraryItem cannot be resolved to a variable and 2nd the method getTitle() is undefined for the class Library... I can't understand why :( Commented Apr 19, 2015 at 11:09
  • Does LibraryItem have a method getTitle? Commented Apr 19, 2015 at 11:11
  • @Boris the Spider Yes Commented Apr 19, 2015 at 11:12
  • Well, you need to pass in the actual List you are sorting too I suppose - Collections.sort(List, Comparator). Commented Apr 19, 2015 at 11:14

4 Answers 4

2

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));
Sign up to request clarification or add additional context in comments.

3 Comments

too verbose - see Comparator.comparing(...) as @Boris_the_Spider proposed above
@harshtuna yep, it's awesome but requires java 8
why stick to legacy versions? just to support ugly enterprise stuff which stuck in Java 1.5?
1

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

Comments

0

Streams way (the original collection untouched)

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

Collection sort in place (i.e. with side effects)

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

Comments

-1

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

3 Comments

This sums salaries for for employees. How does this in any way help?
I just wanted to help him with a sample. for reference I have quoted the url, please read before voting down.
Link only answers a not appreciated. And your simple example is completely irrelevant. Don't assume I haven't read your answer, carefully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.