Conceptual Questions
1. What are the main features introduced in Java 8?
● ambda Expressions: Enable functional programmingby writing functions inline.
L
● Stream API: Process collections in a functional style.
● Predicate,
Functional Interfaces: Interfaces with a single abstractmethod (e.g.,
Function
).
● NullPointerException.
ptional: Avoid
O
● Default Methods: Add default implementations in interfaces.
● Date and Time API: Improved handling of dates andtimes.
● Method References: Simplified syntax for calling methods.
2. What are functional interfaces?
● unctional interfaces have exactly one abstract method.
F
● Support lambda expressions and method references.
● Examples:
○
Runnable( v
oid run() )
○ Predicate<T>(
b
oolean test(T t)
)
○ Function<T, R>(
R
apply(T t)
)
Streamand its key methods.
3. Explain
● Streamrepresents a sequence of elements for processing.
A
● Intermediate Operations(return a Stream):
○
filter() : Filter elements based on a condition.
○ map()
: Transform elements.
○ sorted() : Sort elements.
● Terminal Operations(consume the Stream):
○
collect() : Convert to a collection.
○ forEach()
: Perform an action.
○ reduce()
: Aggregate elements.
map()and
4. What is the difference between flatMap()
?
●
map()
: Transforms each element, returning a streamof streams.
●
flatMap()
: Transforms and flattens nested structuresinto a single stream.
Optionalin Java 8?
5. What is
U
● NullPointerException
sed to avoid .
● Methods:
○
of(value) Optionalwith a non-null value.
: Create an
○
empty() Optional
: Create an empty .
○
ifPresent()
: Perform an action if a value is present.
defaultmethods work in interfaces?
6. How do
● Add new methods to interfaces with a default implementation.
xample:
E
interface MyInterface {
default void show() {
System.out.println("Default Method");
}
}
●
Collectors
7. What is the purpose of ?
C
● ollectorsis a utility for reducing streams.
● Common collectors:
○
toList() toSet()
, : Convert to a list or set.
○
joining()
: Concatenate strings.
○
groupingBy()
: Group elements by a key.
○
partitioningBy()
: Partition elements into two groups.
java.util.Date
8. How does the Date and Time API differ from ?
LocalDate
● Immutable and thread-safe classes: LocalTime
, LocalDateTime
, .
●
DateTimeFormatterfor parsing and formatting.
ZonedDateTime
● Zone-aware classes like .
9. What are method references in Java 8?
A
● shorthand for lambda expressions.
● Types:
Class::methodName
○ Static methods:
instance::methodName
○ Instance methods:
ClassName::new
○ Constructors:
parallelStream()in Java 8?
10. What is
● Processes elements in parallel for better performance in large datasets.
xample:
E
List<Integer> numbers = Arrays.asList(1, 2, 3);
numbers.parallelStream().map(n -> n * 2).forEach(System.out::println);
●
Coding Problems with Solutions
Lambda Expressions
1. Print a list using .
ist<String> names = Arrays.asList("Alice", "Bob", "Charlie");
L
names.forEach(name -> System.out.println(name));
2. Filter even numbers from a list using Streams.
ist<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
L
List<Integer> evens = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evens); // Output: [2, 4, 6]
3. Find the maximum value in a list using Streams.
ist<Integer> numbers = Arrays.asList(10, 20, 30, 40);
L
int max = numbers.stream()
.max(Integer::compare)
.orElse(0);
System.out.println(max); // Output: 40
4. Convert a list of strings to uppercase.
ist<String> names = Arrays.asList("alice", "bob");
L
List<String> upperNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upperNames); // Output: [ALICE, BOB]
groupingBy()
5. Group strings by their length using .
ist<String> names = Arrays.asList("Alice", "Bob", "Charlie");
L
Map<Integer, List<String>> grouped = names.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println(grouped); // Output: {3=[Bob], 5=[Alice], 7=[Charlie]}
reduce()
6. Find the sum of numbers using .
ist<Integer> numbers = Arrays.asList(1, 2, 3, 4);
L
int sum = numbers.stream()
.reduce(0, Integer::sum);
System.out.println(sum); // Output: 10
groupingBy()
7. Count word occurrences in a list using .
ist<String> words = Arrays.asList("apple", "banana", "apple");
L
Map<String, Long> wordCount = words.stream()
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
System.out.println(wordCount); // Output: {apple=2, banana=1}
joining()
8. Concatenate strings using .
List<String> words = Arrays.asList("Java", "is", "awesome");
String sentence = words.stream()
.collect(Collectors.joining(" "));
System.out.println(sentence); // Output: Java is awesome
9. Sort employees by salary.
class Employee {
String name;
int salary;
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
public String toString() {
return name + ": " + salary;
}
}
List<Employee> employees = Arrays.asList(
new Employee("Alice", 5000),
new Employee("Bob", 3000),
new Employee("Charlie", 4000)
);
List<Employee> sorted = employees.stream()
.sorted(Comparator.comparingInt(e -> e.salary))
.collect(Collectors.toList());
System.out.println(sorted); // Output: [Bob: 3000, Charlie: 4000, Alice: 5000]
10. Find the first non-repeated character in a string.
tring input = "swiss";
S
Character result = input.chars()
.mapToObj(c -> (char) c)
.filter(ch -> input.indexOf(ch) == input.lastIndexOf(ch))
.findFirst()
.orElse(null);
System.out.println(result); // Output: w
Stream.findFirst()and
11. What is the difference between Stream.findAny()
?
● findFirst() :
○ Returns the first element of the Stream.
○ Suitable for ordered Streams.
●
findAny() :
○ Returns any element of the Stream.
○ Suitable for parallel Streams where order doesn't matter.
12. What are the different types of Streams in Java 8?
● Sequential Stream:
○ Processes elements sequentially in a single thread.
● Parallel Stream:
○ Processes elements in multiple threads for faster computation.
13. Can we use multiple filters in a single Stream?
es, you can chain multiple filters:
Y
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
.filter(n -> n > 2)
.filter(n -> n % 2 == 0)
.forEach(System.out::println); // Output: 4
●
reduce()in Java 8 Streams with an example.
14. Explain
●
reduce()is used for aggregation, like summing orconcatenating elements.
xample:
E
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
int sum = numbers.stream()
.reduce(0, Integer::sum); // Start with 0
System.out.println(sum); // Output: 10
●
15. How does Java 8 handle default methods in case of multiple inheritance?
● If multiple interfaces provide the same default method:
○ The class must override the method to resolve the conflict.
xample:
E
interface A {
default void display() {
System.out.println("A");
}
}
interface B {
default void display() {
System.out.println("B");
}
}
class C implements A, B {
public void display() {
A.super.display(); // Choose A's display method
}
}
●
16. What are some best practices for using Streams in Java 8?
● void using Streams for small collections (traditional loops are better).
A
● UseparallelStream()only when working with largedatasets.
● Prefermethod referencesover complex lambda expressionsfor readability.
● Use terminal operations (
collect reduce
, ) to consumethe Stream.
Coding Problems
Stream.distinct()to remove duplicates froma list.
11. Use
ist<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
L
List<Integer> distinctNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(distinctNumbers); // Output: [1, 2, 3, 4, 5]
12. Find all elements starting with "A" in a list.
ist<String> names = Arrays.asList("Alice", "Bob", "Annie", "Alex");
L
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
System.out.println(filteredNames); // Output: [Alice, Annie, Alex]
13. Sort a list of strings alphabetically and in reverse order.
ist<String> names = Arrays.asList("Charlie", "Alice", "Bob");
L
List<String> sortedNames = names.stream()
.sorted() // Ascending
.collect(Collectors.toList());
System.out.println(sortedNames); // Output: [Alice, Bob, Charlie]
List<String> reversedNames = names.stream()
.sorted(Comparator.reverseOrder()) // Descending
.collect(Collectors.toList());
System.out.println(reversedNames); // Output: [Charlie, Bob, Alice]
flatMap()
14. Flatten a list of lists using .
List<List<Integer>> nestedList = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5),
Arrays.asList(6, 7, 8)
);
List<Integer> flatList = nestedList.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flatList); // Output: [1, 2, 3, 4, 5, 6, 7, 8]
Collectors.partitioningBy()to separate evenand odd numbers.
15. Use
ist<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
L
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println(partitioned); // Output: {false=[1, 3, 5], true=[2, 4, 6]}
16. Find the second highest number in a list.
ist<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);
L
int secondHighest = numbers.stream()
.sorted(Comparator.reverseOrder())
.skip(1) // Skip the highest
.findFirst()
.orElseThrow(() -> new RuntimeException("No second highest found"));
System.out.println(secondHighest); // Output: 40
17. Count the frequency of characters in a string using Streams.
tring input = "java";
S
Map<Character, Long> frequency = input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println(frequency); // Output: {a=2, j=1, v=1}
18. Generate an infinite Stream of even numbers and limit it to 10 elements.
List<Integer> evenNumbers = Stream.iterate(0, n -> n + 2)
.limit(10)
.collect(Collectors.toList());
System.out.println(evenNumbers); // Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
19. Check if all elements in a list are greater than a given number.
ist<Integer> numbers = Arrays.asList(10, 20, 30, 40);
L
boolean allGreater = numbers.stream()
.allMatch(n -> n > 5);
System.out.println(allGreater); // Output: true
20. Find the average of a list of numbers.
ist<Integer> numbers = Arrays.asList(10, 20, 30, 40);
L
double average = numbers.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0.0);
System.out.println(average); // Output: 25.0
Stream.iterate()
21. Generate the Fibonacci series using .
Stream.iterate(new int[]{0, 1}, f -> new int[]{f[1], f[0] + f[1]})
.limit(10)
.map(f -> f[0])
.forEach(System.out::print); // Output: 01123581321
Collectors.groupingBy()
22. Group employees by department using .
class Employee {
String name;
String department;
Employee(String name, String department) {
this.name = name;
this.department = department;
}
}
List<Employee> employees = Arrays.asList(
new Employee("Alice", "HR"),
new Employee("Bob", "IT"),
new Employee("Charlie", "HR"),
new Employee("David", "IT")
);
ap<String, List<Employee>> groupedByDepartment =
M
employees.stream()
.collect(Collectors.groupingBy(emp ->
emp.department));
groupedByDepartment.forEach((dept, emps) -> {
ystem.out.println(dept + ": " + emps.stream().map(e ->
S
e.name).collect(Collectors.toList()));
});
23. Count occurrences of each word in a sentence.
String sentence = "Java is fun and Java is powerful";
Map<String, Long> wordCount = Arrays.stream(sentence.split(" "))
.collect(Collectors.groupingBy(word -> word,
ollectors.counting()));
C
ystem.out.println(wordCount); // Output: {Java=2, is=2, fun=1, and=1,
S
powerful=1}
24. Find the longest word in a list.
List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
String longestWord = words.stream()
.max(Comparator.comparingInt(String::length))
.orElse(null);
System.out.println(longestWord); // Output: banana
flatMap()
25. Merge two lists into a single list using .
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(4, 5, 6);
List<Integer> mergedList = Stream.of(list1, list2)
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(mergedList); // Output: [1, 2, 3, 4, 5, 6]
26. Find the first element in a Stream greater than 10.
List<Integer> numbers = Arrays.asList(5, 8, 12, 3, 20);
int first = numbers.stream()
.filter(n -> n > 10)
.findFirst()
.orElse(-1);
System.out.println(first); // Output: 12
27. Find the minimum value in a list using Streams.
List<Integer> numbers = Arrays.asList(10, 20, 5, 15);
int min = numbers.stream()
.min(Integer::compareTo)
.orElseThrow(() -> new RuntimeException("No minimum value
found"));
System.out.println(min); // Output: 5
Stream.generate()to create a list of randomnumbers.
28. Use
List<Double> randomNumbers = Stream.generate(Math::random)
.limit(5)
.collect(Collectors.toList());
System.out.println(randomNumbers);
29. Find duplicate elements in a list using Streams.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 2, 3);
Set<Integer> duplicates = numbers.stream()
.filter(n -> Collections.frequency(numbers, n) > 1)
.collect(Collectors.toSet());
System.out.println(duplicates); // Output: [2, 3]
30. Partition a list into prime and non-prime numbers.
List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9, 10);
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(num ->
isPrime(num)));
System.out.println(partitioned);
static boolean isPrime(int num) {
if (num <= 1) return false;
r eturn IntStream.rangeClosed(2, (int) Math.sqrt(num)).noneMatch(n ->
num % n == 0);
}
Stream.flatMap()to process nested collections.
31. Use
List<List<String>> nestedList = Arrays.asList(
Arrays.asList("Alice", "Bob"),
Arrays.asList("Charlie", "David")
);
List<String> flatList = nestedList.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flatList); // Output: [Alice, Bob, Charlie, David]
32. Calculate the factorial of a number using Streams.
int number = 5;
int factorial = IntStream.rangeClosed(1, number)
.reduce(1, (a, b) -> a * b);
System.out.println(factorial); // Output: 120
Stream.skip()and
33. Use Stream.limit()to extractsublists.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
List<Integer> sublist = numbers.stream()
.skip(2) // Skip the first 2 elements
.limit(3) // Take the next 3 elements
.collect(Collectors.toList());
System.out.println(sublist); // Output: [3, 4, 5]
Collectors.teeing()to compute two operationson a Stream.
34. Use
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Map<String, Double> result = numbers.stream()
.collect(Collectors.teeing(
Collectors.summingDouble(n -> n),
Collectors.averagingDouble(n -> n),
(sum, avg) -> Map.of("Sum", sum, "Average", avg)
));
System.out.println(result); // Output: {Sum=15.0, Average=3.0}
35. Find all palindromic strings in a list.
ist<String> words = Arrays.asList("madam", "racecar", "java", "level",
L
"hello");
List<String> palindromes = words.stream()
.filter(word -> word.equals(new
tringBuilder(word).reverse().toString()))
S
.collect(Collectors.toList());
System.out.println(palindromes); // Output: [madam, racecar, level]