人数が増えたとき人数を更新しわすれない? List<Integer> scores = ...; int sum = 0; sum += scores.get(0); sum += scores.get(1); sum += scores.get(2); sum += scores.get(3); double ave = (double)sum/4;
ave = (double)sum/scores.size(); 平均を求める – Stream APIバージョン final int sum = scores.stream() .mapToInt(x -> x) .sum(); final double ave = (double)sum/scores.size(); final double ave = scores.stream() .collect(Collectors.averagingDouble(x -> x)); Ex 1. Ex 2. Ex 3.
List<Customer> tokyoCustomers = new ArrayList<>(); for (int i = 0; i < customers.size(); i++) { var customer = customers.get(i); if (customer.prefecture().equals("Tokyo")) { tokyoCustomers.add(customer); } } 例 条件に合致した要素を抽出 – for文バージョン