i have three ArrayList of Integers type, i want to find largest integer value from those ArrayList
ArrayList<Integer> data1 = new ArrayList<>();
data1.add(20);
data1.add(30);
data1.add(40);
data1.add(51);
data1.add(71);
data1.add(212);
data1.add(203);
ArrayList<Integer> data2 = new ArrayList<>();
data2.add(56);
data2.add(67);
data2.add(267);
data2.add(257);
data2.add(367);
data2.add(363);
data2.add(233);
ArrayList<Integer> data3 = new ArrayList<>();
data3.add(36);
data3.add(12);
data3.add(366);
data3.add(53);
data3.add(124);
data3.add(256);
data3.add(203);
System.out.println("Largest Value = ");
is there any simplest way to find largest value from multiple arraylist? Thanks !
This is a really simple one, that doesn't require any re-structuring of the data, and doesn't use streams. Not that there's anything wrong with using streams, but just to offer an alternative solution.
Integer maxValue = Math.max(Collections.max(data1), Math.max(Collections.max(data2), Collections.max(data3)));
Combine the last two lists into the first one, and then use Collections.max()
:
data1.addAll(data2);
data1.addAll(data3);
Integer maxValue = Collections.max(data1);
List<Integer> newList = new ArrayList<>(data1);
newList.addAll(data2);
newList.addAll(data3);
Collestions.sort(newList);
Collections.reverse(newList);
System.out.println("max: " + newList.get(0));
or
Integer max(Integer element, List<Integer> list) {
Integer result = element;
for (Integer num : list) {
if (num > result) {
result = num;
}
}
return result;
}
Using max
method:
Integer result = max(data1.get(0), data1);
result = max(result, data2);
result = max(result, data3);
System.out.println("max: " + result);
Use java.util.stream
Integer maxValue = Stream.of(data1, data2, data3)
.flatMap(Collection::stream)
.max(Integer::compare)
.get();
If you like streams & co:
import package java.util.stream.Stream;
[...]
int max = Stream.of(data1.stream(), data2.stream(), data3.stream())
.flatMap(i -> i)
.mapToInt(i -> i)
.max()
.getAsInt();
Another streaming example, not flat-mapping to a single stream
Integer max = Stream.of(data1, data2, data3)
.map(list -> list.stream().max(Integer::compare).get())
.max(Integer::compare).get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.