我有一个ArrayList,其中包含对象,如:
buffer_head
构造函数是:(其中" Type"是枚举)
private static List<Movies> movie= new ArrayList<Movies>();
现在我知道如何获得完整的第一个对象,使用:
public Movies(String name, int budget, int a, String director, Type action)
但是我想以某种方式得到哪部电影的预算最多,并打印出它的导演。我怎么能这样做?
答案 0 :(得分:1)
假设Movies
使用getBudget
方法返回预算,
你可以得到电影流,
按预算按降序排序,
并找到第一场比赛,如果有的话:
Movies first = movie.stream()
.sorted(Comparator.comparing(Movies::getBudget).reversed())
.findFirst()
.orElseThrow(() -> new IllegalStateException("List of movies is empty!"));
如果您只想获得导演,可以在.map(...)
之后使用.sorted(...)
提取导演。
答案 1 :(得分:0)
您只需通过执行以下操作对列表进行排序
列出movies = movie.stream()。sorted(Comparator.comparing(Movie :: getBudget()));
在此行之后执行此操作
movies.get(0);
答案 2 :(得分:0)
老式的方式怎么样:浏览列表并跟踪到目前为止您看过的预算最高的电影。当您看到列表中的所有电影时,您就会知道哪一部电影的预算最高。
以下是一种方法:
Movie largestBudgetMovie = null;
for (Movie m : movie) {
if (largestBudgetMovie == null ||
m.getBudget() > largestBudgetMovie.getBudget())
largestBudgetMovie = m;
}
if (largestBudgetMovie == null)
System.out.println("The list was empty");
else
System.out.println("The most expensive movie on my list was directed by " +
largestBudgetMovie.getDirector());
这是另一个:
if (movie.size() > 0) {
Movie largestBudgetMovie = movie.get(0);
for (int i = 1; i < movie.size(); ++i) {
Movie m = movie.get(i);
if (m.getBudget() > largestBudgetMovie.getBudget())
largestBudgetMovie = m;
}
System.out.println("The most expensive movie on my list was directed by " +
largestBudgetMovie.getDirector());
}
else
System.out.println("The list was empty");