Finding max using lambda java

Viewed 156

Here is my code :

public static void Max(List<List<String>> data) {
    data.forEach(d -> String max = Collections.max(Arrays.asList(d.getMax(5))));
}

The result I get:

70
75
76

How can I get only the maximum number?

2 Answers

You can use Comparator.comparing to compare the 2nd index and parse as Integer when compare then get the second index element from the list.

String res = Collections.max(data, 
               Comparator.comparing(e -> Integer.parseInt(e.get(2)))).get(2);

A more simple way:

int max = Integer.MIN_VALUE;
        for (int i = 0; i < data.size(); i++) {
            for (int j = 0; j < data.get(i).size(); j++) {
                max = Integer.max(Integer.parseInt(data.get(i).get(j)), max);
            }
        }
        System.out.println(max);

This way we comb through every member of each list and by invoking max() we get the max number, which is then displayed in the console.

Related