Java / Java8 streams
1. Write a Java8 program to remove null from a stream.
Refer the below program. import java.util.List ; import java.util.stream.Collectors ; import java.util.stream.Stream ; public class FilterNull { public static void main(String[] args) { Stream < String > streamOfStrings = Stream . of( "One" , "Two" , "Three" , null, "Five" , null); List < String ...
2. What is a stream in Java8?
A stream represents a sequence of elements and supports a different kind of operations to perform computations upon those elements. In Java 8, each Stream class represents a single-use sequence of data and supports several I/O operations.
3. Explain: IllegalStateException, stream has already been operated upon or closed.
A Stream should be operated o only once. A Stream implementation may throw IllegalStateException if it detects that the Stream is being reused. Whenever a terminal operation is called on a Stream object, the instance gets consumed and closed. Therefore, it is allowed to perform a single operation...
4. How do I resolve IllegalStateException when Stream is reused?
Create new stream whenever required as shown below. public class LargestAndSmallest { public static void main (String [] args) { Supplier < Stream < Integer >> myIntStream = () -> Stream.of( 1 , 2 , 3 , 44 , 556 , - 1 , 0 , 2234 ); System.out.println( "Largest = " + myIntStream.get().reduce(Integ...
5. How to override equals method in Java8?
See the below code snippet. @Override public boolean equals (Object obj) { return Optional . ofNullable(obj) . filter(that -> that instanceof Employee) . map(that -> (Employee) that) . filter(that -> this . fName . equals(that . fName)) . filter(that -> this . lName . equals(that . lName)) . isPr...
6. Can you explain what is default method in Java 8?
Default methods are the method defined in the interfaces with method body and using the default keyword. The implementing class may choose to override the default method or they may invoke the default method itself. Default method can call methods from the interfaces they are enclosed in. Also in...
7. What type of variable be accessed in a lambda expression?
Inside a lambda expression, you can access final variables and also effectively final variables. Effectively final variables are initialized once however not marked final, second initialization lead to compilation error when used inside a lambda expression.
8. Is forEach a terminal operation?
Yes. After the operation is performed, the stream pipeline is considered consumed, and no longer be used.
9. Types of stream operations.
Stream operations are 2 types, intermediate and terminal operations, and together they form stream pipelines. Intermediate operations return new are eam which allows you to call multiple operations in a form of a query. This operation does not get executed until a terminal operation is invoked. A...
10. Types of intermediate operations in Stream.
There are 2 types, stateful and stateless . Stateful intermediate operations maintain information (state) from a previous invocation to use again in a future invocation of the method. For example, Stream.distinct() needs to remember the previous elements it encountered, thus have to store state f...
11. Explain stream pipeline and its components.
A steam pipeline is a sequence of aggregate operations. Examples of aggregate operations include filter and forEach. A pipeline has the following components: A source represented by collection, an array, a generator function, or an I/O channel. 0 or more intermediate operations such as filter tha...
12. Differences Between Aggregate Operations such as forEach and Iterators.
stream.forEach and iterator works similar in terms of functionality. The below are the differences in how they operate. Aggregate operations. Iterator. They process elements from the stream not directly on the collection.. Iterator directly process the collection . Aggregate operation use interna...
13. What are reduction operations?
Reduction operations are terminal operations such as average, sum, min, max, and count that return one value by combining the contents of a stream. There are 2 general-purpose reduction operations, Stream.reduce and Stream.collect .
14. Why lambda expression is needed?
Lambda expressions are used to define inline implementation of a functional interface, an interface with a only one (non static) method, that eliminates the need of anonymous class and brings a very simple and powerful functional programming capabilities into Java.
15. Explain limit and skip methods in Java8 streams.
The limit(long n) method of java.util.stream.Stream object performs stream reduction operation and returns a reduced stream of first n elements from the stream. The skip(long n) method of java.util.stream.Stream object returns a stream of remaining elements after skipping first n elements. Both m...
16. One programming question related to Java streams. I have an Array of Employees object (includes empName, sex, age, city). Can you write a Java program using Java streams concepts to find the number of Employees in each City? For example, Employees in Mumbai: 35 like that. Thanks in Advance.
Thanks for your question. Consider the below example. Kindly share your feedback/suggestions in the comment section. package net.javapedia.streams; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; class Employee { public Employee(String ...
17. Explain Java8 Collectors partitioningBy method.
Java 8 Collectors.partitioningBy method accepts a predicate and returns a Collector by partitioning the element of the stream using Predicate so it will have 2 keys at most in Map. The key of the map can be only true and false and each key's value is a list of elements. public static
18. How do I pass custom message for the exception when thrown using orElseThrow method?
We can pass the custom message to the Exception constructor when created as shown below. orElseThrow(() -> new EntityNotFoundException("Entity doesn't Exist")); Example: import java.util.Optional ; public class OrElseThrowCustomMessage { public static void main(String[] args) { Optional < String ...
19. What is Optional class in java?
Inspired from Haskell and Scala, Java SE 8 introduces a new class in util package, java.util.Optional, whose instance hold an object so that it either contains a value or not (empty). It eliminates NullPointerException and the null check constructs. Example of an empty optional: Optional
20. What is the difference between Java8 Collections and Stream?
Collection contains its elements but stream doesn't. Stream act on a view while elements are actually stored in the Collection or array. Any change made on streams does not reflect on the underlying collection.
21. Is Java8 stream lazy?
Yes. Java8 stream does NOT execute just by defining the steam pipeline. Stream works only when you call a terminal operation on the Stream.
22. Explain the Collectors framework in Java8.
Java 8 Collectors main components are, Stream.collect() method, Collector interface, and Collectors class. collect() method, a terminal operation in Stream interface, is a special case of reduction operation called mutable reduction operation because it returns mutable result container such as Li...
23. Which functional interface represents a function that accepts a double valued argument and produces an int valued result?
DoubleToIntFunction functional interface accepts a double-valued argument and produces an int-valued result.
24. Which functional interface represents an operation that accepts a single int valued argument and returns no result?
IntConsumer.
25. How do you sort a list of strings using Java 8 lambda expression?
Refer the below program. public class SortinJava8 { public static void main (String [] args) { List < String > names = Arrays.asList( new String [] { "Banana" , "Apple" , "Cantalope" }); Collections.sort(names, (s1, s2) -> s1.compareTo(s2)); System.out.println(names); } }
26. Difference between Collection and Stream in Java 8.
Collection has its own elements, but Stream doesn't have. Stream works on a view, which points to elements that are actually stored by Collection or array. Any changes made on Stream don't reflect on the original Collection.
27. What is a Predicate interface?
A Predicate is a functional interface that represents a function, which takes an Object and returns a boolean. It is used in several Stream methods like filter(), which uses Predicate to filter unwanted elements. public boolean test(T object){ return boolean; } Predicate has test() method which t...
28. Difference between Java interface (normal) and functional interface.
Java interface can have any number of abstract methods however functional interface must have only one abstract method.
29. Difference between the findFirst() and findAny() method.
The findFirst() method returns the first element that meets the criterion (i.e). Predicate, while the findAny() method return any element that meets the criterion. findAny() is very useful while working with a parallel stream.
30. What is a filter() method in Java 8?
The filter method is used to filter elements that satisfy a certain condition that is specified using a Predicate function. A predicate function is nothing but a function that takes an Object and returns a boolean. public class Java8FilterExample { public static void main (String [] args) { List ...
31. Difference between the old and new Date Time API in Java 8.
Old API. New Date and Time API (Java 8). Date object is mutable. In Java 8, all date and time classes like LocalDate, LocalTime, or LocalDateTime are Immutable. SimpleDateFormat is not thread-safe. Formatter is thread-safe. Old Date and Calendar API has just one class Date to represent date and t...
32. What are the Java8 features?
Java 8 provides the following features: DateTime API, Lambda expressions, Method references, Functional interfaces, Stream API, Base64 Encode Decode, Default and Static methods in interface, Optional class, Collectors class, ForEach() method in Iterable interface , Nashorn JavaScript Engine, Para...
33. Difference between map and flatmap in Java.
In Java streams, the primary difference is that map() performs a one-to-one transformation, returning a stream of the same size as the input, while flatMap() handles one-to-many transformations and flattens nested data structures into a single-level stream. Parameter map() flatMap() Mapping One e...
34. Can you use the standard Java Ternary Operator in Reactive Code?
Yes. You can use the traditional ternary operator for simple conditional assignments within methods called in a reactive chain, provided the conditions are synchronous and local. import reactor.core.publisher.Mono ; public class TernaryExample { public Mono < String > getGreeting(String name) { /...
35. Difference between distinct and distinctUntilChanged in RxJava.
Distinct and distinctUntilChanged both filter RxJS streams based on value equality. distinct filters out all duplicates across the entire history , storing all past values in memory. distinctUntilChanged only suppresses consecutive duplicates (comparing current to previous) , making it highly eff...