Java Notes -1
Java Notes -1
Conceptual Questions
L
● ambda Expressions: Enable functional programmingby writing functions inline.
● 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.
F
● unctional interfaces have exactly one abstract method.
● Support lambda expressions and method references.
● Examples:
○
Runnable(void run() )
○
Predicate<T>(
boolean test(T t)
)
○
Function<T, R>(
R apply(T t)
)
●
map()
: Transforms each element, returning a streamof streams.
●
flatMap()
: Transforms and flattens nested structuresinto a single stream.
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.
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 .
A
● shorthand for lambda expressions.
● Types:
Class::methodName
○ Static methods:
instance::methodName
○ Instance methods:
ClassName::new
○ Constructors:
xample:
E
List<Integer> numbers = Arrays.asList(1, 2, 3);
numbers.parallelStream().map(n -> n * 2).forEach(System.out::println);
●
Lambda Expressions
1. Print a list using .
ist<String> names = Arrays.asList("Alice", "Bob", "Charlie");
L
names.forEach(name -> System.out.println(name));
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
●
●
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?
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
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)
);
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
Stream.iterate()
21. Generate the Fibonacci series using .
.limit(10)
Collectors.groupingBy()
22. Group employees by department using .
class Employee {
String name;
String department;
this.name = name;
this.department = department;
}
}
);
.collect(Collectors.groupingBy(emp ->
emp.department));
});
.max(Comparator.comparingInt(String::length))
.orElse(null);
flatMap()
25. Merge two lists into a single list using .
.flatMap(List::stream)
.collect(Collectors.toList());
.orElse(-1);
.min(Integer::compareTo)
System.out.println(min); // Output: 5
.limit(5)
.collect(Collectors.toList());
System.out.println(randomNumbers);
.collect(Collectors.toSet());
.collect(Collectors.partitioningBy(num ->
isPrime(num)));
System.out.println(partitioned);
}
Arrays.asList("Alice", "Bob"),
Arrays.asList("Charlie", "David")
);
List<String> flatList = nestedList.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
Stream.skip()and
33. Use Stream.limit()to extractsublists.
.collect(Collectors.toList());
.collect(Collectors.teeing(
));
.collect(Collectors.toList());