使用lambda在Java中查找最大值

huangapple go评论71阅读模式
英文:

Finding max using lambda java

问题

这是我的代码:

public static void Max(List<List<String>> data) {
    data.forEach(d -> {
        int max = d.stream()
                   .mapToInt(Integer::parseInt)
                   .max()
                   .orElse(0);
        System.out.println(max);
    });
}

我得到的结果:

70
75
76

如何仅获取最大的数字?

英文:

Here is my code :

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

The result I get:

70
75
76

How can I get only the maximum number?

答案1

得分: 2

你可以使用Comparator.comparing来比较第2个索引,并在比较时解析为整数,然后从列表中获取第2个索引元素。

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

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 -&gt; Integer.parseInt(e.get(2)))).get(2);

答案2

得分: 0

一个更简单的方法:

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);

通过这种方式,我们遍历每个列表的每个成员,并通过调用 max() 函数获得最大数,然后在控制台中显示出来。

英文:

A more simple way:

int max = Integer.MIN_VALUE;
        for (int i = 0; i &lt; data.size(); i++) {
            for (int j = 0; j &lt; 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.

huangapple
  • 本文由 发表于 2020年10月2日 17:35:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/64169340.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定