Rectangle { private final int length; private final int width; public Rectangle(int length, int width) { this.length = length; this.width = width; } public int length() { return this.length; } public int width() { return this.width; } public boolean equals(Object obj) {...} // 省略(各フィールドを使った適切な処理) public int hashCode() {...} // 省略(各フィールドを使った適切な処理) public String toString() {...} // 省略(各フィールドを使った適切な処理) } public record Rectangle(int length, int width) { }
length, int width) { public Rectangle { if (length < 0 || width < 0) { throw new IllegalArgumentException(); } } public Rectangle(int length) { this(length, 0); } } public record Rectangle(int length, int width) { public int area() { return length * width; } }
https://docs.oracle.com/javase/jp/17/docs/api/java.base/java/lang/String.ht ml#translateEscapes() String text = "a¥¥n¥¥tb"; System.out.println(text); // a¥n¥tb assertThat(text.translateEscapes()).isEqualTo("a¥n¥tb"); System.out.println(text.translateEscapes()); // a // b
書けるので、読みやすくなる int num = "1".transform(Integer::parseInt); // これと同じ int num = Integer.parseInt("1"); int num = "12#34".transform(this::clean).transform(Integer::valueOf);
(day) { case MONDAY: case FRIDAY: case SUNDAY: numLetters = 6; break; case TUESDAY: numLetters = 7; break; case THURSDAY: case SATURDAY: numLetters = 8; break; case WEDNESDAY: numLetters = 9; break; default: throw new IllegalStateException(); } // switch式 int numLetters = switch (day) { case MONDAY, FRIDAY, SUNDAY -> 6; case TUESDAY -> 7; case THURSDAY, SATURDAY -> 8; case WEDNESDAY -> 9; default -> throw new IllegalStateException(); };
switch (day) { case MONDAY, FRIDAY, SUNDAY -> 6; case TUESDAY -> 7; case THURSDAY, SATURDAY -> 8; case WEDNESDAY -> 9; default -> throw new IllegalStateException(); }; // コロンcaseラベル+yield int numLetters = switch (day) { case MONDAY: case FRIDAY: case SUNDAY: yield 6; case TUESDAY: yield 7; case THURSDAY: case SATURDAY: yield 8; case WEDNESDAY: yield 9; default: throw new IllegalStateException(); };
case MONDAY, FRIDAY, SUNDAY: System.out.println(6); break; case TUESDAY: System.out.println(7); break; case THURSDAY, SATURDAY: System.out.println(8); break; case WEDNESDAY: System.out.println(9); break; default: throw new IllegalStateException(); }
// takeWhileだと、無制限なStreamでも条件に一致しなくなった時点で止めてくれる IntStream.iterate(2, x -> x * 2) .takeWhile(x -> x <= 100) .toArray(); // filterだと、条件に一致しなくてもStream処理は継続される=終わらない IntStream.iterate(2, x -> x * 2) .filter(x -> x <= 100) .toArray();