Interview Q&A / Java
Java interview questions
Collections, the JVM, strings, exceptions and threads, the backbone of most campus placement rounds.
Prefer rapid revision? Practise Java short interview answers →
- What is the difference between map and flatMap in Java streams?
map transforms each element into exactly one new element. flatMap transforms each element into a stream and then merges all those streams into one flat stream, which is how you unpack lists inside lists.
IntermediateQuick answer1 min read - Why does a Java stream do nothing until a terminal operation is called?
Intermediate operations like filter and map only describe the pipeline. Work starts when a terminal operation such as collect, count or forEach is called, and elements then flow through the whole pipeline one at a time.
IntermediateQuick answer1 min read - Write Java code to find the second highest distinct number in a list.
Sort the distinct values in descending order, skip the first, and take the next, returning an Optional because there may be no second value. The stream version is O(n log n); a single loop tracking two maximums is O(n).
IntermediateQuick answerCoding1 min read - Write Java code to group a list of names by their first letter using streams.
Use Collectors.groupingBy with a classifier that returns the first character, and pass TreeMap::new if you want the keys sorted. It makes one pass, so O(n) time and O(n) space.
IntermediateQuick answerCoding1 min read