ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
List<String> l = new ArrayList<>(List.of("ccc", "ee", "a", "bb", "d"));
l.sort(Comparator.comparingInt(String::length));
System.out.print(l);- A. [a, d, bb, ee, ccc]
- B. [d, a, ee, bb, ccc]
- C. [a, bb, ccc, d, ee]
- D. [a, d, ee, bb, ccc]
Correct answer: D. [a, d, ee, bb, ccc]
The comparator looks only at length, so a/d and ee/bb tie. List.sort is guaranteed STABLE, so tied elements keep their original relative order (a before d, ee before bb) instead of being put in alphabetical order.
More OOP with C++ and Java questions
- What is printed? java int[] c = {0}; Runnable r = () -> c[0]++; r.run(); r.run(); System.out.print(c[0]);
- What is printed? java List<Integer> a = new ArrayList<>(List.of(1, 2)); List<Integer> b = new LinkedList<>(List.of(1, 2))…
- What is printed? java Queue<Integer> q = new ArrayDeque<>(); q.add(1); q.add(2); q.offer(3); q.poll(); System.out.print(q.peek() + " " +…
- What is printed? java System.out.print(Stream.of(1, 2, 3).reduce(10, Integer::sum));
- What is printed? java long n = Stream.of(List.of(1, 2), List.of(2, 3)) .flatMap(List::stream).distinct().count(); System.out.print(n);
- What is printed? java Map<Boolean, List<Integer>> m = Stream.of(2, 4) .collect(Collectors.partitioningBy(x -> x > 5))…