Home > Enterprise >  Specific element in a List Java
Specific element in a List Java

Time:10-31

So I want to output the max PRICE of a List.My method who finds the max Price

Now I need the i-1 element of the for loop to get the index and then print it as a List how should it be ? enter image description here

I have some exprience in C# where I think this works there but in Java it doesnt. :/

CodePudding user response:

Java does not support overwriting operators, so BookList1[i-1] is not allowed, because BookList1 is not an array. You need to use BookList1.get(i-1) to get the element on that index. In C# you are allowed to use BookList1[i], because C# lists implement this operator. This was already introduced in C , but never im Java.

CodePudding user response:

You can use the following approach to get most expensive:

public void getMostExpensive (List<Book> bookList){
    Book expensive = bookList.get(0);
    for (Book book : bookList) {
            if(book.getPrice() > expensive.getPrice())
                expensive = book;
    }
    System.out.println(expensive.getPrice());
}
  • Related