ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
Map<String, Integer> m = new HashMap<>();
m.compute("a", (k, v) -> v == null ? 1 : v + 1);
m.compute("a", (k, v) -> v == null ? 1 : v + 1);
m.computeIfPresent("b", (k, v) -> v + 100);
System.out.print(m + " ");
m.compute("a", (k, v) -> null);
System.out.print(m.containsKey("a") + " " + m.size());- A. {a=2} false 0
- B. {a=2} true 1
- C. {a=2, b=100} false 1
- D. {a=1} false 0
Correct answer: A. {a=2} false 0
compute receives the current value (null the first time), so a becomes 1 then 2. computeIfPresent does nothing for a missing key. Returning null from the remapping function removes the mapping.
More OOP with C++ and Java questions
- What is printed? java Map<String, String> h = new HashMap<>(); h.put("k", null); System.out.print(h.size() + " "); Map<String, String> c =…
- What is printed? java List<Integer> e = Collections.emptyList(); System.out.print(e.size() + " "); e.add(1);
- What is printed? java System.out.print(String.valueOf((Object) null) + " "); System.out.print(String.valueOf(null));
- What is printed? java // static methods of the main class: static void f(int... a) { System.out.print("V"); } static void f(Integer a…
- What is printed? java // static methods of the main class: static void f(double d) { System.out.print("D"); } static void f(Object o) {…
- Which line fails to compile? java // static methods of the main class: static void g(long l) { } static void h(Long l) { } // in main…