網頁

2020/5/3

Java 加總整數陣列 sum List<Integer> and int array

Java加總List<Integer>int[]array陣列中全部元素值的方法如下。

import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);

        int result = sum(intList);
        System.out.println(result); // 15

        // Java 8
        result = intList.stream().reduce(0, Integer::sum);
        System.out.println(result); // 15

        result = intList.stream().mapToInt(e -> e).sum();
        System.out.println(result); // 15

        // --------------------------------------------------

        int[] ints = {1, 2, 3, 4, 5};
        result = sum(ints);
        System.out.println(result); // 15

        // Java 8
        result = Arrays.stream(ints).sum();
        System.out.println(result); // 15

    }

    public static int sum(List<Integer> intList) {
        if (intList == null || intList.size() == 0) {
            return 0;
        }
        int sum = 0;
        for (int n : intList) {
            sum += n;
        }
        return sum;
    }

    public static int sum(int[] ints) {
        if (ints == null || ints.length == 0) {
            return 0;
        }
        int sum = 0;
        for(int n : ints) {
            sum += n;
        }
        return sum;
    }
    
}

沒有留言:

張貼留言