'How to find the maximum value from a ArrayList which has both int and double values?
I tried this what am i doing wrong or what should i do.I am a beginner CS student trying to solve this question. The error i get is in image format here: Error i get when i try to runprogram
import java.util.*;
public class maximum
{
public static void main(String[]args)
{
//Creates new array list
ArrayList list = new ArrayList();
//Adds the numbers in the ArrayList
Collections.addAll(list,5,2,-8,9,5.5,7,0);
//Stores the highest number in new arraylist
ArrayList highestNumber = new ArrayList();
highestNumber.add(Collections.max(list));
// Prints highestNumber
System.out.println(highestNumber);
}
}
Solution 1:[1]
First step: Change the List type to Number, which is the superclass of all java's boxed numeric primitives.
Then, find the max by comparing Number#doubleValue():
ArrayList<Number> list = new ArrayList<>();
Collections.addAll(list, 5, 2, -8, 9, 5.5, 7, 0);
ArrayList<Number> highestNumber = new ArrayList<>();
highestNumber.add(Collections.max(list, Comparator.comparing(Number::doubleValue)));
Since all int may be safely converted to a Double, this code is completely safe to use with a mix of doubles and ints.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
