ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
Map<Integer, String> m = Stream.of("ab", "cd", "e")
.collect(Collectors.toMap(String::length, s -> s));
System.out.print(m);- A. {2=cd, 1=e}
- B. {2=ab, 1=e}
- C. {1=e, 2=abcd}
- D. An IllegalStateException is thrown (duplicate key 2)
Correct answer: D. An IllegalStateException is thrown (duplicate key 2)
Collectors.toMap without a merge function throws IllegalStateException when two elements map to the same key. Passing a third argument such as (x, y) -> x resolves collisions.
More OOP with C++ and Java questions
- Why is the comparator (a, b) -> a - b unsafe for sorting arbitrary int values in Java?
- What is printed? java String s = "ab"; StringBuilder sb = new StringBuilder("ab"); System.out.print(s.equals(sb) + " " +…
- What happens when this class is compiled? java class Code implements Comparable<String>, Comparable<Integer> { public int compareTo(String…
- Which statement about Java anonymous classes is correct?
- Which lines fail to compile? java // Java 10 or later var list = new ArrayList<>(); // L1 list.add(1); list.add("a"); // L2 var x; // L3…
- What happens when this is compiled? java // Java 17 sealed class Shape permits Circle, Square { } final class Circle extends Shape { }…