You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UnnamedPatternsPreview1.java 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import java.awt.*;
  2. import java.util.List;
  3. import java.util.PriorityQueue;
  4. import java.util.Queue;
  5. import java.util.stream.Collectors;
  6. import java.util.stream.Stream;
  7. /**
  8. * Examples taken from <a href="https://openjdk.org/jeps/443">JEP 443</a>
  9. */
  10. public class UnnamedPatternsPreview1 {
  11. public static void main(String[] args) {
  12. // An enhanced for loop with side effects
  13. int acc = 0;
  14. final int LIMIT = 2;
  15. for (Order _ : List.of(new Order(), new Order(), new Order())) {
  16. if (acc < LIMIT)
  17. acc++;
  18. }
  19. System.out.println(acc);
  20. // The initialisation of a basic for loop can declare unnamed local variables
  21. for (int i = 0, _ = sideEffect(); i < 2; i++) {
  22. System.out.println(i);
  23. }
  24. // An assignment statement, where the result of the expression on the right hand side is not needed
  25. Queue<Integer> q = new PriorityQueue<>(List.of(1, 2, 3, 4, 5, 6));
  26. while (q.size() >= 3) {
  27. var x = q.remove();
  28. var y = q.remove();
  29. var _ = q.remove();
  30. System.out.println(new Point(x, y));
  31. }
  32. // The same unnamed variable name '_' can be used in multiple assignment statements
  33. q = new PriorityQueue<>(List.of(1, 2, 3, 4, 5, 6));
  34. while (q.size() >= 3) {
  35. var x = q.remove();
  36. var _ = q.remove();
  37. var _ = q.remove();
  38. System.out.println(new Point(x, 0));
  39. }
  40. // Unnamed variables can be used in one or multiple catch blocks
  41. String s = "123xy";
  42. try {
  43. int i = Integer.parseInt(s);
  44. System.out.println(i);
  45. } catch (NumberFormatException _) {
  46. System.out.println("Bad number: " + s);
  47. } catch (Exception _) {
  48. System.out.println("Unexpected error");
  49. }
  50. // Try with resources
  51. try (var _ = ScopedContext.acquire()) {
  52. System.out.println("Doing something within scoped context");
  53. }
  54. // A lambda whose parameter is irrelevant
  55. System.out.println(
  56. Stream.of("one", "two", "three")
  57. .collect(Collectors.toMap(String::toUpperCase, _ -> "NODATA"))
  58. );
  59. }
  60. static int sideEffect() {
  61. System.out.println("side effect");
  62. return 42;
  63. }
  64. static class Order {}
  65. static class ScopedContext implements AutoCloseable {
  66. public static ScopedContext acquire() {
  67. return new ScopedContext();
  68. }
  69. @Override
  70. public void close() {
  71. System.out.println("Closing scoped context");
  72. }
  73. }
  74. }