如何通过另一个班级的分组打印一个班级的数组列表?

时间:2019-01-29 14:35:46

标签: java arraylist methods aggregate

我正在尝试基于另一类的参数之一来打印一类中的arraylist。这可能吗?

import java.util.ArrayList;

public class TVShow {

    private String title;
    private String summary;
    private String releaseDate;
    private ArrayList<Episode> episodeList;


    public TVShow(String title, String summary, String releaseDate) {
        this.title = title;
        this.summary = summary;
        this.releaseDate = releaseDate;
        this.episodeList = new ArrayList<>();
    }

    public void addEpisode(Episode episode) {
        episodeList.add(episode);
    }

    public printEpisodesInSeason(int seasonNr) { 
        // How can I make this method access the other class and 
        // print the episodeList by season number?
        for (Episode episode : episodeList) {
             return System.out.println(episode.);
        }
    }
}


public class Episode {

    private int episodeNr;
    private int seasonNr;
    private String eTitle;
    private int runTime;

    public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
        this.episodeNr = episodeNr;
        this.seasonNr = seasonNr;
        this.eTitle = eTitle;
        this.runTime = runTime;
    }
}

1 个答案:

答案 0 :(得分:0)

编辑:我想我误解了这个问题。您只想打印特定季节的情节。可以通过在episodeList上应用过滤器功能来完成此操作,如下所示:

for (Episode episode : episodeList.stream().filter(episode -> episode.getSeasonNr() == seasonNr).collect(Collectors.toList())) 
{ ... }

这当然是假设您在我编辑答案之前应用如下所述的getter setter模式。

filter函数采用匿名函数,并将其应用于集合的所有成员。这样,仅返回具有用户提供的季节编号的情节。然后,foreach循环遍历结果集合。

您可以通过定义以下内容来公开Episode的成员:

public class Episode {

    public int episodeNr;
    public int seasonNr;
    public String eTitle;
    public int runTime;

    public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
        this.episodeNr = episodeNr;
        this.seasonNr = seasonNr;
        this.eTitle = eTitle;
        this.runTime = runTime;
    }
}

但是,这被视为不良做法。更好的方法是通过在Episode类中定义方法以返回该类的字段的值,例如:

public class Episode {

    public int episodeNr;
    public int seasonNr;
    public String eTitle;
    public int runTime;

    public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
        this.episodeNr = episodeNr;
        this.seasonNr = seasonNr;
        this.eTitle = eTitle;
        this.runTime = runTime;
    }

    public String getTitle() {
        return this.eTitle;
    }
}

这种做法称为getter和setter,它对代码的封装产生积极影响。然后,您可以通过调用episode.getTitle()来获得Episode成员的价值。