-2

I have an ArrayList, with objects in it, like:

private static List<Movies> movie= new ArrayList<Movies>();

And the contructor is: (where the "Type" is an enum)

public Movies(String name, int budget, int a, String director, Type action)

Now I know how to get the full first object, with:

Movies firstelement = movie.get(0);

But I would like to get somehow which movie had the most budget, and print it's director. How could I do that?

  • Possible duplicate of [Collections sort(List,Comparator super T>) method example](https://stackoverflow.com/questions/14154127/collections-sortlistt-comparator-super-t-method-example) – vinS Dec 10 '17 at 05:00

3 Answers3

1

Assuming Movies has a getBudget method to return the budget, you can get the stream of movies, sort by budget in descending order, and find the first match, if any:

Movies first = movie.stream()
  .sorted(Comparator.comparing(Movies::getBudget).reversed())
  .findFirst()
  .orElseThrow(() -> new IllegalStateException("List of movies is empty!"));

If you want to get just the director, you could extract that with a .map(...) after .sorted(...).

janos
  • 120,954
  • 29
  • 226
  • 236
0

All you need is to sort your list by doing the following

List movies = movie.stream().sorted(Comparator.comparing(Movie::getBudget()));

After this line do this

movies.get(0);
AbdusSalam
  • 485
  • 5
  • 13
  • First, `comparing(Movie::getBudget())` won't compile; it should be `comparing(Movie::getBudget)`. Second, the expression doesn't actually sort `movie`; the result is a stream that has all the movies in sorted order, but the actual list `movie` remains untouched. So `movie.get(0)` afterward just returns whatever movie was already (and still is) first on the list. – Kevin Anderson Dec 10 '17 at 07:06
0

How about the old-fashioned way: run through the list and keep track of the highest-budget movie you've seen so far. When you've seen all the movies on the list, you'll know which one has the highest budget of all.

Here's one way to do it:

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

Here's another:

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"); 
Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21