|| Java 8 ||
1. Lambda Expression
- Lambda Expression is an anonymous function.Its a function without name and does not belongs to any class. (just same like arrow function in Javascript)
- Lambda expression is maninly used to implement functional interfaces.
- Functional InterFace
- functional interface were introduced in java 8
- AN interface that contains exactly one abstract method is known as a functional interface.
- Functional interface can have any number of default , static methods but can contains only one abstract method.
- Lambda vs Method
1. Method is always belongs to class or objects in Java where Lambda does not belongs to any class or object.
- Method Have Name, Parameter list , Body , Return type.
Ex : public int addition(int a,int b) { return a + b ; } //
2. Lambda
Syntax : addble withLambdaD = (int a, int b) -> (a+b);
- No Name : as lambda is an anonymous function so no need to have a name
- Parameter list
- Body : This is the main part of the function.
- No return type - Ypu dont need mention return type in the lambda expression . THe java8+ compiler is infer the return type by checking the code.
Lambda Expression Syntax :
() -> { }
Package Name : Lambda Expression
--------------------------------------------------------------------------------
2. Functional Interfaces
What we will learn ?
- How to define functinal interface using @FunctionalInterface annotaion
- How to use Lambda expression to implement functional interface
- We will see some predefined functional interfaces with examples
- Runnable functioanl interface Examples
1. What is Functional Interface
- Functional InterFace
- functional interface were introduced in java 8
- AN interface that contains exactly one abstract method is known as a functional interface.
- Functional interface can have any number of default , static methods but can contains only one abstract method.
- We use Java 8 provide the @FunctionalInterface annotation to mark an interface as a functional interface.
Package Name : Functional
--------------------------------------------------------------------------------
3. Method References
- Java provides a new feature called method reference in Java 8.
- Method reference is used to refer method of the functional interface. It is a compact and easy form of a Lambda Expression.
- Each time when you are using a lambda expression to just referrring a method , you can replace lambda expression with a method reference.
- Method references help to point to methods by their names. A method reference is described using "::" symbol. A method reference can be used to point the following types of methods −
- Static methods
- Instance methods
- Constructors using new operator (TreeSet::new)
Syntax :
Printable p = System.out::println;
p.methodName("Jay Shivray");
Types of Method References
There are four types of method reference in Java.
1. Method Reference to static method
- Syntax : Class :: StaticMethodName
2. Method Reference to an instance method of particular object.
- Syntax : Object :: instanceMethodName
3. Method Reference to instace method of an arbitary object of specific type.
- Syntax : Class :: instanceMethodName
4. Method Reference to constructor
- Syntax : ClassNames :: new
--------------------------------------------------------------------------------
4. Java Optional Class
- As a Java programmer ,we are familiar with NullPointerException
- Java 8 has introduced a new Optional utility class in java.utll package.THis class can help in avoiding null ckecks and NullPointerException exception.
- You can view Optional as a single-value container that either contains a value or doesn't (it is then said to be "empty")
- Optional is a container object used to contain not-null objects.
- Optional object is used to represent null with absent value.
- This class has various utility methods to facilitate code to handle values as ‘available’ or ‘not available’ instead of checking null values.
- It is introduced in Java 8 and is similar to what Optional is in Guava.
--------------------------------------------------------------------------------
5. Default and Static Method in Interface .
interface IFace{
Default void DMethod()
{
Default Method
}
Static void DMethod()
{
Static Method
}
}
--------------------------------------------------------------------------------
6. Java 8 Stream API
Source Reference : Stream Reference detail
( https://medium.com/@alibaba-cloud/process-collections-easily-with-stream-in-java-8-c222c06408d8 )
- Stream represents a sequence of object of object from a source, which supports aggregate operations.
- Java Provides a new Additional package in Java 8 called java.util.stream.
- This Package consists of classes , interfaces , and an enum to allow functional-style operation on the elements. You can use stream by importing java.util.stream package in Your Programs .
- Stream provides a high-level abstraction for Java collection operations and expressions by querying data from databases similar to SQL statements.
- Stream API can significantly improve the productivity of Java programmers and allow them write effective, clean, and concise code.
- Stream is a new abstract layer introduced in Java 8. Using stream, you can process data in a declarative way similar to SQL statements. For example, consider the following SQL statement.
SELECT max(salary), employee_id, employee_name FROM Employee
- Java 8 introduced the concept of stream that lets the developer to process data declaratively and leverage multicore architecture without the need to write any specific code for it.
Characteristics and Advantages of Java Streams :
1. No storage : A Stream is not a data structure , but only a view of a data source , which can be an array, a Java container or an I/O channel.
2. Lazy execution : Operations on a Stream will not be executed immediately. They will be executed only when users really need results.
3. Consumable : The elements of a stream are only visited once during the life of a stream. Once traversed, a Stream is invalidated, just like a container iterator. You have to regenerate a new Stream if you want to traverse the Stream again.
4. A Stream is functional in nature. Any modifications to a Stream will not change the data sources.
- For example, filtering a Stream does not delete filtered elements, but generates a new Stream that does not contain filtered elements.
How Stream Works ?
Source - Filter - Sort - Map - collect
Source - create - intermediete - terminal - output
1. Stream Creation
- There are Many method can be used to create a Stream.
1. Create a Stream by Using Existing Collections
- The stream method in java 8 can convert a collection into stream.
2. Create a stream by using the stream method
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> streamFromList = numbers.stream();
int[] array = {1, 2, 3, 4, 5};
IntStream streamFromArray = Arrays.stream(array);
Stream<String> streamFromIO = Files.lines(Paths.get("file.txt"));
Stream<Integer> streamFromGenerator = Stream.generate(() -> 42);
2. Stream Intermediate Operations
- A stream may have many intermediate operations, which can be combined to form a pipeline.
- Each intermediate operation is like a worker on the pipeline.
- Each worker can process the Stream.
- Intermediate operations return a new Stream.
- Intermediate operations are used to transform, filter, or manipulate the elements of a Stream. They return a new Stream as a result.
List of Common intermediate operations :
- Filter : filter the item according the given predicate(Condition ) : Input type - Predicate
- map : Processes items and transforms : Input type - Function
- limit : limit the result : Input type - int
- sorted : sort items inside stream : Input type - Comparator
- distinct : Remove duplicate items according to equals method of the given type.
1. filter : The filter method is used to filter elements by specified conditions.
2. map : The map method maps each elements to its corresponding result.
numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
numbers.stream().map( i -> i*i).forEach(System.out::println); //9,4,4,9,49,9,25
3. limit/skip : Limit returns the first N elements in a Stream (first element up 4). Skip abandons the first N elements in a Stream (it skip the 4 ).
4. sorted : The sorted method sorts elements in a Stream.
5. distinct : The distinct method is used to remove duplicates.
3. Stream Terminal Operations
- Terminal operations produce a final result or a side effect. They trigger the processing of the Stream and do not return another Stream.
- Stream terminal operations also return a Stream. How can we convert a Stream into the desired type? For example, count elements in a Stream and convert that Stream into a collection. To do this, we need terminal operations.
- A terminal operation will consume a Stream and generate a final result.
- The following table lists the common terminal operations.
- forEach(Consumer<T>): The forEach method iterates through elements in a Stream.
- count : The count method counts the elements in a Stream.
- collect(Collector<T, A, R>): reduce operation that can accept various parameters and accumulate the stream elements into a summary result:
- reduce(BinaryOperator<T>): Performs a reduction on the elements of the Stream.
Stream soruce <- create stream instance -> Intermediate Operations -> Terminal Operation -> Operational Result .
new functional interfaces introduced
--------
Difference Between CompletableFuture And Future In Java
- Basic Characteristics
- Future:
- Introduced in Java 5, Future represents the result of an asynchronous computation.
- It provides methods to check if the computation is done, to wait for its completion, and to retrieve the result. However, its capabilities are quite basic and limited.
- CompletableFuture
- Introduced in Java 8, CompletableFuture is an enhancement of Future.
- It not only represents a future result but also provides a plethora of methods to compose, combine, execute asynchronous tasks, and handle their results without blocking.
- Method Of Use
- Future:
- It is generally used with an ExecutorService, and we get a Future object when we submit tasks to the executor.
- However, it doesn’t allow us to define any computation steps to be executed once the computation is finished.
- The get() method is blocking, which means it waits until the task is completed and can make the application less responsive.
- CompletableFuture:
- It can be used as a Future and also allows us to attach callbacks via methods like thenApply, thenAccept, and thenRun.
- These methods let us execute additional actions upon completion of the original task, in a non-blocking fashion.
- CompletableFuture can also be manually completed.
- Exception Handling
- Future:
- Does not provide a built-in mechanism for handling exceptions.
- Exception handling needs to be implemented externally. Exceptions are caught during the get() method call.
- CompletableFuture:
- Provides methods like exceptionally and handle to deal with exceptions in a chain of asynchronous tasks.
- Allows defining a recovery or fallback mechanism within the computation chain.
- Blocking vs. Non-Blocking
- Future:
- Primarily relies on blocking operations (get()) for retrieving the result of the asynchronous computation.
- CompletableFuture:
- Encourages non-blocking programming. It allows us to process results with functions and actions that get applied asynchronously, thus enhancing the responsiveness of your application.
- Use Cases
- Future: Suitable for simple asynchronous operations where we need to perform tasks in a separate thread and retrieve the results later.
- CompletableFuture: Ideal for complex asynchronous programming needs, including chaining multiple asynchronous operations, error handling, combining results, and implementing non-blocking algorithms.
-------
Thread Pool :
A thread pool reuses previously created threads to execute current tasks and offers a solution to the problem of thread cycle overhead and resource thrashing. Since the thread is already existing when the request arrives, the delay introduced by thread creation is eliminated, making the application more responsive.
------
- What is the difference between a terminal operation and an intermediate operation in a stream?
- An intermediate operation on a stream returns a new stream, while a terminal operation consumes the stream and produces a result.
- Map : The map() method in Java 8 streams is used to transform each element in a stream into a new element
- filter(): The filter() method in Java 8 streams is used to filter out elements from a stream based on a specified condition.
- reduce(): The reduce() method in Java 8 streams is used to combine all the elements in a stream into a single result.
- The reduce() method allows developers to perform complex operations on data in a simple and efficient way.
- collect(): The collect() method in Java 8 streams is used to collect the elements in a stream into a specified data structure.
- flatMap() : The flatMap() method in Java 8 streams is used to flatten a stream of streams(Nested Stream) into a single stream.
- distinct() : The distinct() method in Java 8 streams is used to remove duplicate elements from a stream.
- parallel(): The parallel() method in Java 8 streams is used to process the elements in a stream in parallel.
- toMap() : The toMap() method was added to the Collectors class in Java 8 to provide a way of collecting a stream of objects to a Map object.
Spliterator interface : The Spliterator interface was introduced in Java 8 to provide a way to split a collection of data into smaller parts.
- The Optional class in Java 8 is a container object that may or may not contain a value. It is used to avoid null pointer exceptions.
|| Java 8 Interview Question ||
1. What are all features of Java8 did you used ?
1. Functional Interface(include dafault & static method)
2. Lambda Expression
3. Stream
4. CompletableFuture
5. Java Date TIme API
2. What is Functional Inteface ?
- An Functional interface that contains only one abstract method . It can have any number of default and static methods.
Default Method :
- From Java8 Interfaces can contain the default method, which is useful to provide the common implementation of a method to all the classes/interfaces which implement these interfaces.
- In Java8 we can have any number of default methods.
Static Method :
- Java8 Interfaces also introduced a static method for the interface , this is similar to the static method of the class.
- We cannot override the static method in the implementation class.
- Static methods are useful to implement utility functionalities that do not belong to any particular implementation class.
- What are some commonly used types of functional interface ?
- Consumer — Accepts argument but does not return any value. (similar as a Void)
- Predicate — Performs test and returns a boolean value.(return Boolean)
- Supplier — doesn’t take any argument but returns a value. (Opposite to Consumer)
- Function — Transfers argument into returnable value.
3. Can you tell fer functaionl inteface which is already there before Java 8.
- Runnable
- Callable
- Comparator (Interviewer might ask about equals() method inside comparatot so equalt method override from Object class that the answer. )
4. Can you write one functional interface ?
-
@FunctiaonlInterface
interface Demo
{
public int sum(int num);
}
// here we can generic function for all types of data
Function <Interge, String> function = (num) -> "Output is "+num;
sysout(function.apply(85)); // output : output is 85.
5. Can we extends functinal inteface from another functional interface ?
- No, if another interface contain asbtract method . and Yes , when another interface contain only static and default method.
[ A functional interface can’t extend another interface which has an abstract method, because it will void the fact that a functional interface allows only one abstract method, however functional interface can inherit another interface if it contains only static and default methods in it. ]
6. What are the all functional interface introduced in java 8 ?
- Function , predicate , Consumer , supplier.
7. what is Lambda Expression ?
- Lambda Expression basically express the instace of functional interface.
- Lambda is short and small block of code which take a parameter and return the resultant values.
- Lambda expression provides a clear and concise way to represent method of a functional using an expression.
- Lambda Expressions can be defined as methods without names i.e anonymous functions.
- But unlike methods, neither they have names nor they are associated with any particular class.
8. What is the advantages and disadvantages of Lambda expression it ?
Advantages :
- 1. Avoid writing anonymous implementation
- 2. It saves a Lot of code
- 3. can make code less readable for complex logic.
Disadvantages :
- 1. Hard to use without an IDE
- 2. Complex to debug.
9. what is Stream API
- Stream API introduced in java 8 and it is used to process collections of objects with functioanl style of coding using lambda expression.
- Stream API is used to process collections of objects.
- Streams can be used for filtering, collecting, printing, and converting from one data structure to another, etc.
- Note: Streams are present in java’s utility package named java.util.stream
10. What is Stream in Java 8 ?
- A stream is sequence of objects that supports various methods which can be popelined to produce the desired result.
- Stream represents a sequence of object of object from a source , which supports aggregate operations.
- streams can be defined as operations on data. They are the sequence of elements from a source which support data processing operations.
- Using Java 8 Streams, you can write most complex data processing queries without much difficulties.
- The features of Java stream are -
- a stream is not a data structure instead it takes input from the collection , arrays or I/O channels.
- Stream don't change the original data structure, they only provide the result as per the pipelined method.
Stream soruce <- create stream instance -> Intermediate Operations -> Terminal Operation -> Operational Result .
11. What is method reference in Java 8 ?
- method reference is a shorthand notation of a lambda expression to call a method .
12. Spell(tell) few stream method you used in your project ?
- filter
- forEach
- sorted
- map
- flatMap
- reduce
- groupingBy ( interview programming question )
- Count
- collect
13. When to use map & flatMap ?
-
1. map()
2. flapMap()
1. It processes stream of values.
1. It processes stream of stream of values.
2. It does only mapping.
2. It performs mapping as well as flattening.
3. It’s mapper function produces single value for each input value.
3. It’s mapper function produces multiple values for each input value.
4. It is a One-To-One mapping.
4. It is a One-To-Many mapping.
5. Data Transformation : From Stream<T> to Stream<R>
5. Data Transformation : From Stream<Stream<T> to Stream<R>
6. Use this method when the mapper function is producing a single value for each input value.
6. Use this method when the mapper function is producing multiple values for each input value.
16. Stream vs Parallel Stream ?
-
- Sequential Stream : it use on Single core of our System.
- Parallel stream : it use Multiple core of our system.
Ex :
Sequ : IntStream.range(1, 10).forEach(i -> System.out.println("Sequencial Stream : "+Thread.currentThread().getName()+i));
Para : IntStream.range(1, 10).parallel().forEach(i -> System.out.println("Parallel Stream : "+Thread.currentThread().getName()+i));
17. What is CompletableFuture ?
- CompletableFuture is used for asynchoronous programming in java.
- Asynchronous programming is a means of writing non-blocking code by running a task on a seperate thread than the main application thread and notifying the main thread about its progress, completion or failure.
- CompletableFuture is a class in java.util.concurrent package that implements the Future and CompletionStage Interface.
- It represents a future result of an asynchronous computation.
- It provides a number of methods to perform various operations on the result of the async computation.
- We can use it to compose multiple asynchronous operations, handle errors and exceptions, and combine multiple CompletableFutures into one
Ex : p.s.v.main()
{
CompletableFuture<String> greetingFuture = CompletableFuture.supplyAsync(() -> {
// some async computation
return "Hello from CompletableFuture";
});
System.out.println(greetingFuture.get());
}
18. Why CompletableFuture and why not Future Object ?
1. It Cannot be manually completed.
2. Multiple Futures cannot be chained together.
3. You can not combine multiple futures together.
4. No Exception Handling.
19. How to decide Thread Pool Size ?
- CPU Intensive Tasks
- IO Intensive Tasks
21 .What is the purpose of Java 8 Optional class?
- Java 8 Optional class is used represent an absence of a value i.e null.
- Before Java 8, if-constructs are used to check for null value. But, Optional class gives better mechanism to handle null vale or absence of a value.
Why was the Optional class introduced in Java 8?
- The Optional class was introduced in Java 8 to provide a way of handling null values in a more concise and expressive way. The Optional class allows developers to write code that is more robust and bug-free.
22. What are the differences between collections and streams?
-
1. Collections
2. Streams
1. Collections are mainly used to store and group the data.
1. Streams are mainly used to perform operations on data.
2. You can add or remove elements from collections.
2. You can’t add or remove elements from streams.
3. Collections have to be iterated externally.
3. Streams are internally iterated.
4. Collections can be traversed multiple times.
4. Streams are traversable only once.
5. Collections are eagerly constructed.
5. Streams are lazily constructed.
6. Ex : List, Set, Map…
6. Ex : filtering, mapping, matching…
23. What are reducing operations? Name the reducing operations available in Java 8 streams?
- Reducing operations are the operations which combine all the elements of a stream repeatedly to produce a single value.
- For example, counting number of elements, calculating average of elements, finding maximum or minimum of elements etc.
- Following Reducing operations available in Java 8 streams are,
1. min() : Returns minimum element
2. max() : Returns maximum element
3. count() : Returns the number of elements
4. collect() : Returns mutable result container
24. What are the matching operations available in Java 8 streams?
-
1. anyMatch() : Returns true if any one element of a stream matches with given predicate
2. allMatch() : Returns true if all the elements of a stream matches with given predicate
3. noneMatch() : Returns true only if all the elements of a stream doesn’t match with given predicate.
25. What are searching / finding operations available in Java 8 streams?
-
1. findFirst() : Returns first element of a stream
2. findAny() : Randomly returns any one element in a stream
26. Which type of resource loading do Java 8 streams support? Lazy Loading OR Eager Loading?
-
- Lazy Loading.
27. What do you mean by pipeline of operations? What is the use of it?
- A pipeline of operations consists of three things – a source, one or more intermediate operations and a terminal operation.
- Pipe-lining of operations let you to write database-like queries on a data source. Using this, you can write more complex data processing queries with much of ease.
28. Can we consider streams as another type of data structure in Java? Justify your answer?
- You can’t consider streams as data structure. Because they don’t store the data. You can’t add or remove elements from the streams.
29. Why static methods are introduced to interfaces from Java 8?
- Java API developers have followed the pattern of supplying an utility class along with an interface to perform basic operations on such objects.
- With the introduction of static methods to interface, such utility classes will disappear gradually and methods to perform basic operations will be kept as static methods in interface itself.
30. What are default methods of an interface? Why they are introduced?
- Default methods of an interface are the concrete methods for which implementing classes need not to give implementation. They inherit default implementation.
- Default methods are introduced to add extra features to current interfaces without disrupting their existing implementations.
- For example, stream() is a default method which is added to Collection interface in Java 8.
- If stream() would have been added as abstract method, then all classes implementing Collection interface must have implemented stream() method which may have irritated existing users.
- To overcome such issues, default methods are introduced to interfaces from Java 8.
31. Along with functional interfaces which support object types, Java 8 has introduced functional interfaces which support primitive types. For example, Consumer for object types and intConsumer, LongConsumer, DoubleConsumer for primitive types. What do you think, is it necessary to introduce separate interfaces for primitive types and object types?
- Yes, If an input or output to an functional interface is a primitive type then using functional interfaces which support primitive types improves performance rather than using functional interfaces which support object types. Because it removes unnecessary boxing and unboxing of data.
32. Which functional interface do you use if you want to perform some operations on an object and returns nothing?
- Consumer.
33. Which functional interface is the best suitable for an operation which creates new objects?
- Supplier.
34. What is the difference between Predicate and BiPredicate?
- Predicate is a functional interface which represents a boolean operation which takes one argument.
- BiPredicate is also functional interface but it represents a boolean operation which takes two arguments.
35. Why was the Date and Time API introduced in Java 8?
- The Date and Time API was introduced in Java 8 to provide a more robust and flexible way of handling dates and times.
- The new API allows developers to handle dates and times in an easier way.
Programs
14. Write a Program (WAP) using stream to find frequency of each character in a given string ?
- str.chars()
.mapToObj(c ->(char) c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()))
.forEach((c,f) -> System.out.println( c +" is no time "+f));
15. Assume you have list of employee in various dept, WAP to find highest paid employye from each dept.
-
Comparator<Employee> highsa = Comparator.comparing(Employee::getSalary);
Map<String, Optional<Employee>> empMap = empList.stream()
.collect(Collectors.groupingBy(Employee::getDept,
Collectors.reducing(BinaryOperator.maxBy(highsa)))
);
import java.lang.reflect.Constructor;
import java.security.Identity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.smartcardio.CommandAPDU;
import javax.swing.text.Highlighter;
// 14. Write a Program (WAP) using stream to find frequency of each
character in a given string ?
// 15. Assume you have list of employee in various dept,
WAP to find highest paid employye from each dept.
class Employee {
String name;
String dept;
int salary;
public Employee(String name, String dept, int salary) {
this.name = name;
this.dept = dept;
this.salary = salary;
}
public String getName() {
return name;
}
public String getDept() {
return dept;
}
public int getSalary() {
return salary;
}
public void setName(String name) {
this.name = name;
}
public void setDept(String dept) {
this.dept = dept;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Override
public String toString() {
return "name : " + name + " , dept : " + dept + " ,salary " + salary;
}
}
public class CountFrequencyEachCharacter {
public static void main(String[] args) {
// 14. Write a Program (WAP) using stream to
find frequency of each character in a given string ?
countFrequency();
// 15. Assume you have list of employee in various dept,
WAP to find highest paid employye from each dept.
highestSalary();
// 15. Difference between Sequence & Parallel Stream .
SeqAndParallelStream();
}
static void countFrequency() {
String str = "Datta";
// str.chars()
// .mapToObj(c ->(char) c) // Convert the String to an IntStream
// .collect(Collectors.groupingBy(c -> c, Collectors.counting())) // Group by
// character and count them
// .forEach((Character,frequency) -> System.out.println("Character :"+ Character
// +" - Frequency : "+frequency ));
str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()))
.forEach((c, f) -> System.out.println(c + " is no of time: " + f));
}
static void highestSalary() {
List<Employee> empList = Stream.of(
new Employee("Datta", "IT", 8000),
new Employee("Nagesh", "Finance", 24000),
new Employee("Robot", "Finance", 21000),
new Employee("Ravi", "IT", 8000),
new Employee("Pavan", "Construct", 30000),
new Employee("Babu Bhaiyya", "Construct", 25000),
new Employee("Vishal", "IT", 10000)
).collect(Collectors.toList());
// Comparator<Employee> highSalary = Comparator.comparing(Employee::getSalary);
// Map<String, Optional<Employee>> empMap = empList.stream()
// .collect(Collectors
// .groupingBy(Employee::getDept,
// Collectors.reducing(BinaryOperator.maxBy(highSalary))
// )
// );
// Approach 1
Comparator<Employee> highsa = Comparator.comparing(Employee::getSalary);
Map<String, Optional<Employee>> empMap = empList.stream()
.collect(Collectors.groupingBy(Employee::getDept,
Collectors.reducing(BinaryOperator.maxBy(highsa))));
System.out.println(empMap);
// Approach 2
Map<String, Employee> empMap2 = empList.stream()
.collect(Collectors.groupingBy(
Employee::getDept,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator
.comparingDouble(Employee::getSalary)),
Optional::get)));
System.out.println(empMap2);
}
static void SeqAndParallelStream()
{
System.out.println("Sequencial use only Sigle COre of System");
IntStream.range(1, 10).forEach(i -> System.out.println("Sequencial Stream : "+
Thread.currentThread().getName()+i));
System.out.println("\n========\n");
System.out.println("Parallel stream use Multiple COre of System");
IntStream.range(1, 10).parallel().forEach(i -> System.out.println("Parallel
Stream : "+Thread.currentThread().getName()+i));
}
}
20. WAP to print even and odd using Threads.
-
1. Program 1st
import java.util.concurrent.CompletableFuture;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class EvenOddUsingCompatableFuture {
private static Object object = new Object();
private static IntPredicate evenCount = i -> i % 2 == 0;
private static IntPredicate oddCount = i -> i % 2 != 0;
public static void main(String[] args) {
CompletableFuture.runAsync(() -> EvenOddUsingCompatableFuture.printNumber(evenCount));
CompletableFuture.runAsync(() -> EvenOddUsingCompatableFuture.printNumber(oddCount));
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printNumber(IntPredicate condition) {
IntStream.range(1, 10).filter(condition)
.forEach(EvenOddUsingCompatableFuture::execute);
}
public static void execute(int no) {
synchronized (object) {
try {
System.out.println(Thread.currentThread().getName() + " : " + no);
object.notify();
object.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
2. Program 2nd
public class ThreadEvenAndOdd implements Runnable {
Object object;
static int i = 1 ;
public ThreadEvenAndOdd(Object object)
{
this.object = object;
}
@Override
public void run() {
while(i <= 10)
{
if(i % 2 == 0 && Thread.currentThread().getName().equals("even")) //2,4,6
{
synchronized(object)
{
System.out.println(Thread.currentThread().getName()+" : "+i);
i++;
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if(i % 2 != 0 && Thread.currentThread().getName().equals("odd")) // 1, 3, 5
{
synchronized(object)
{
System.out.println(Thread.currentThread().getName()+" : "+i);
i++;
object.notify();
}
}
}
}
public static void main(String[] args) {
Object obj = new Object();
Runnable th1 = new ThreadEvenAndOdd(obj);
Runnable th2 = new ThreadEvenAndOdd(obj);
new Thread(th1,"even").start();
new Thread(th2,"odd").start();
}
}
1) Given a list of integers, separate odd and even numbers?
2) How do you remove duplicate elements from a list using Java 8 streams?
3) How do you find frequency of each character in a string using Java 8 streams?
4) How do you find frequency of each element in an array or a list?
5) How do you sort the given list of decimals in reverse order?
6) Given a list of strings, join the strings with ‘[‘ as prefix, ‘]’ as suffix and ‘,’ as delimiter?
7) From the given list of integers, print the numbers which are multiples of 5?
8) Given a list of integers, find maximum and minimum of those numbers?
9) How do you merge two unsorted arrays into single sorted array using Java 8 streams?
10) How do you merge two unsorted arrays into single sorted array without duplicates?
11) How do you get three maximum numbers and three minimum numbers from the given list of integers?
12) Java 8 program to check if two strings are anagrams or not?
13) Find sum of all digits of a number in Java 8?
- Find sum of all digits of a number in Array Java 8? // int sum = Arrays.stream(nums).sum();
14) Find second largest number in an integer array?
15) Given a list of strings, sort them according to increasing order of their length?
16) Given an integer array, find sum and average of all elements?
17) How do you find common elements between two arrays?
18) Reverse each word of a string using Java 8 streams?
19) How do you find sum of first 10 natural numbers?
20) Reverse an integer array
21) Print first 10 even numbers
22) How do you find the most repeated element in an array?
23) Palindrome program using Java 8 streams
24) Given a list of strings, find out those strings which start with a number?
25) How do you extract duplicate elements from an array?
26) Print duplicate characters in a string?
27) Find first repeated character in a string?
28) Find first non-repeated character in a string?
29) Fibonacci series
30) First 10 odd numbers
31) How do you get last element of an array?
32) Find the age of a person in years if the birthday has given?
Comments
Post a Comment