There are following way to find 3 max integers in an array in java.
- First convert Arrays to list using Arrays.asList() method.
- Now get the Stream data from List using arrayList.stream() method.
Using Collections.reverseOrder() method :-
- Inside sorted() method Collections.reverseOrder() return the reverse of the natural ordering number.
- The limit(n) method returns a stream not longer than the requested size.
- Now call the Collectors.toList() to store all number inside list.
- Finally, printing on the 3 max integers on the console.
Using compareTo() method :-
- Inside sorted() method compareTo() perform the comparison from second to first number.
- The limit(n) method returns a stream not longer than the requested size.
- Now call the Collectors.toList() to store all number inside list.
- Finally, printing on the 3 max integers on the console.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class FindThreeMax {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(2, 4, 10, 5, 20, 15, 25, 6, 12, 56);
List<Integer> value = numbers.stream().sorted(Collections.reverseOrder()).limit(3).collect(Collectors.toList());
System.out.println("first 3 max number using reverse method :- " + value);
List<Integer> data = numbers.stream().sorted((a, b) -> b.compareTo(a)).limit(3).collect(Collectors.toList());
System.out.println("first 3 max number using compareto method :- " + data);
}
}
Output :-
first 3 max number using reverse method :- [56, 25, 20]
first 3 max number using compareto method :- [56, 25, 20]