簡體   English   中英

Java比較列表與地圖和輸出結果

[英]Java compare list with map and output result

我需要創建清單圖書和地圖獎項。 我的目標是瀏覽清單

The book “<book name>” by <book author> which sold <times published> copies,
received <award for this book> award

如果書單作者等於地圖莎士比亞==莎士比亞,則輸出

The book "Romeo and Juliet" by Shakespeare which sold 4500 copies,
received Too much drama award.

除此以外

The book "Romeo and Juliet" by Shakespeare which sold 4500 copies,
received no award

我是Java新手,我的麻煩是在循環和比較列表時如何向toString發送新的獎勵參數

我的書課

public class Book implements Comparable<Book> {

    private String author;
    private String name;
    private int timesPublished;

    public Book(String author, String name, int timesPublished) {
        this.author = author;
        this.name = name;
        this.timesPublished = timesPublished;
    }

    public int getTimesPublished() {
        return timesPublished;
    }

    public String getName() {
        return name;
    }

    //@Override
    public int compareTo(Book compareBook) {
        if (this.getTimesPublished() == compareBook.getTimesPublished()) {
            return this.getName().toLowerCase().compareTo(compareBook.getName().toLowerCase());
        } else {
            return this.getTimesPublished() - compareBook.getTimesPublished();
        }
    }

    //@Override
    public String toString() {
        return String.format("The book \"%s\" by %s which sold %s copies", name, author, timesPublished);
    }

}

我的主要

public static void main(String[] args) {

    Map<String, String> awards = new HashMap<String, String>();
    awards.put("Shakespeare", "Too much drama");
    awards.put("Swift", "Survival guide");
    awards.put("Austen", "Did not read");
    awards.put("Dumas", "Sweet revenge");

    List<Book> list = new LinkedList<Book>();

    list.add(new Book("Dumas", "The Count of Monte Cristo", 1245));
    list.add(new Book("Shakespeare", "Romeo and Juliet", 4500));
    list.add(new Book("Austen", "Pride", 1000));
    list.add(new Book("Swift", "Aulliver", 1000));
    list.add(new Book("Tolstoy", "Best", 1000));

    Collections.sort(list);

    for(Book temp: list) {
        System.out.println(temp);
    }

}

在book類中為author變量獲取一個getter。 您需要此方法,因為變量是私有的,並且在類外部無法訪問,除非您像這樣創建變量的getter

public String getAuthorName()
{
    return author;
}

然后,當您打印輸出時,可以執行以下操作以檢查地圖中的作者,如果返回null ,則表明該獎項不存在,否則您將獲取獎項地圖中的內容

for(Book temp: list) {
    String awardName = awards.get(temp.getAuthorName());//use the getter to see what the current book's author is
    System.out.println(temp + " received " + (awardName == null ? "no" : awardName) + " award");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM