int[] data ={23, 76, 43, 9, 17, 32, 59}; var result = IntStream.builder(); for (int n : data) { if (n % 2 == 1) continue; result.add(n); } var nums = result.build().toArray(); }
• つまり、処理を追わずにループが読める! for (int n : data) { if (n % 2 == 1) continue; result.add(n); } var result = IntStream.of(data) .filter(n -> n % 2 == 1) .toArray();
入ってくるデータと 出ていくデータを かんがえる import java.util.ArrayList; import java.util.stream.IntStream; void main() { int[] data ={23, 76, 43, 9, 17, 32, 59}; var builder = IntStream.builder(); var window = new ArrayList<Integer>(); var sum = 0; for (var n : data) { sum += n; window.addLast(n); while (window.size() > 3) { sum -= window.removeFirst(); } if (window.size() == 3) builder.add(sum /3); } }
check(String s) { enum State { START, ZERO, INT } var state = State.START; for (char ch : s.toCharArray()) { switch (state) { case START -> { if (ch == '0') state = State.ZERO; else if (ch >= '1' && ch <= '9') state = State.INT; else return false; } case ZERO -> { return false; } case INT -> { if (ch < '0' || ch > '9') return false; } } } return state != State.START; }