271.
272.
Which Java 9 method can you use to create a Set of String
values?
Answer:
Java 9 has added a static factory method to the Set interface.
You can use this to create a Set with String values. The following
code demonstrates this:
Set
months =
Set.of(“January”,”February”,”March”);
This code creates a Set of String values called months. It uses
the String.of() method with the values specified. The
String.of() has several overloaded versions that accept from
0 to 10 arguments as well as a version that accepts varargs.
What will be the output of the following code snippet?
Stream oddNumbers = Stream.iterate(1, num–> num
<= 20, num–> num+2);
oddNumbers.forEach(num–> System.out.print(num+” “));
Answer:
Prior to Java 9, there was a Stream.iterate() method that
created an infinite Stream of values. Java 9 has added an
overloaded version of the Stream.iterate() method that
creates a finite Stream. So, this method accepts an additional
parameter which is a Predicate and stops the stream as soon as
the Predicate is true. So, this code prints the following output:
1 3 5 7 9 11 13 15 17 19