Calculating the sum of all odd array indexes

后端 未结 5 1000
予麋鹿
予麋鹿 2021-01-24 19:00

I want to calculate the sum of all odd array indexes, but I\'m having some trouble finding the right way to do it.

Here\'s my code so far:

    String id         


        
5条回答
  •  情书的邮戳
    2021-01-24 19:42

    There is no Index 13 in this array as in Java index starts from 0. A solution to calculating the sum of all odd array indexes with Java 8 is:

        String id = "9506265088085";
        String[] strArray = id.split("");
    
        int sum = IntStream.range(0, strArray.length)
                .filter(idx -> idx % 2 == 1)
                .map(idx -> Integer.parseInt(strArray[idx]))
                .sum();
    
        System.out.println(sum);
    

提交回复
热议问题