Saturday, April 23, 2022

JAVA_8 Programming 2

Custom ArrayList<E>






3 Different ways to convert arrays to Arraylist in java?






Marker interface in Java


1. Cloneable interface
2. Serializable interface 
3. Remote interface



ConcurrentHashMap 






Feature NameDescription
Lambda expressionA function that can be shared or referred to as an object.
Functional InterfacesSingle abstract method interface.
Method ReferencesUses function as a parameter to invoke a method.
Default methodIt provides an implementation of methods within interfaces enabling 'Interface evolution' facilities.
Stream APIAbstract layer that provides pipeline processing of the data.
Date Time APINew improved joda-time inspired APIs to overcome the drawbacks in previous versions
OptionalWrapper class to check the null values and helps in further processing based on the value.
Nashorn, JavaScript EngineAn improvised version of JavaScript Engine that enables JavaScript executions in Java, to replace Rhino.



Consumer Method Example 





What are the significant advantages of Java 8?

  • Compact, readable, and reusable code.
  • Less boilerplate code.
  • Parallel operations and execution.
  • Can be ported across operating systems.
  • High stability.
  • Stable environment.
  • Adequate support

What is MetaSpace? How does it differ from PermGen?

JVM

PremGen: MetaData information of classes was stored in PremGen (Permanent-Generation) memory type before Java 8. PremGen is fixed in size and cannot be dynamically resized. It was a contiguous Java Heap Memory.

MetaSpace: Java 8 stores the MetaData of classes in native memory called 'MetaSpace'. It is not a contiguous Heap Memory and hence can be grown dynamically which helps to overcome the size constraints. This improves the garbage collection, auto-tuning, and de-allocation of metadata.

Can a functional interface extend/inherit another interface?

A functional interface cannot extend another interface with abstract methods as it will void the rule of one abstract method per functional interface. E.g:

interface Parent { 
public int parentMethod(); 
} 
@FunctionalInterface // This cannot be FunctionalInterface 
interface Child extends Parent { 
public int childMethod(); 
// It will also extend the abstract method of the Parent Interface 
// Hence it will have more than one abstract method 
// And will give a compiler error 
}

It can extend other interfaces which do not have any abstract method and only have the default, static, another class is overridden, and normal methods. For eg:

interface Parent { 
public void parentMethod(){ 
System.out.println("Hello"); 
} 
} 
@FunctionalInterface 
interface Child extends Parent { 
public int childMethod(); 
}



Parallel Streams intro || Stream processing 



Map Vs Flat Map












package com.example.demo.java_8.FlatMap;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FlateMapTest {

public static void main(String[] args) {

List<List<Integer>> list = new ArrayList<>();
list.add(Arrays.asList(1,22,34,2,56));
list.add(Arrays.asList(11,2,7,26,6));
list.add(Arrays.asList(40,20,3,24,5));
list.add(Arrays.asList(100,12,134,67,600));
System.out.println(list);
List<Integer> listNew = list.stream().flatMap(x ->x.stream()).collect(Collectors.toList());
System.out.println(listNew);
List<Integer> listNew_1 = list.stream().flatMap(x ->     x.stream()).sorted().collect(Collectors.toList());
System.out.println(listNew_1);
List<Integer> listNew_2 = list.stream().flatMap(x->x.stream()).sorted().distinct().collect(Collectors.toList());
System.out.println(listNew_2);
}

}

OUTPUT :- 

[[1, 22, 34, 2, 56], [11, 2, 7, 26, 6], [40, 20, 3, 24, 5], [100, 12, 134, 67, 600]]
[1, 22, 34, 2, 56, 11, 2, 7, 26, 6, 40, 20, 3, 24, 5, 100, 12, 134, 67, 600]
[1, 2, 2, 3, 5, 6, 7, 11, 12, 20, 22, 24, 26, 34, 40, 56, 67, 100, 134, 600]
[1, 2, 3, 5, 6, 7, 11, 12, 20, 22, 24, 26, 34, 40, 56, 67, 100, 134, 600]


Java 8 STREAMS Tutorial






2.  Why does Java 8 have functional interfaces?
Because prior to java 8 the implementing 
class of an interface has to implement all the abstract
methods defined in the interface. The functional interface has been 
introduced in Java 8 to support the lambda expression in java 8 
on the other hand it can be said lambda expression is the 
instance of functional interface.
Factorial
package com.example.demo.java_8;

import java.util.stream.LongStream;
public class Factorial_Java_8_2 {
public static long factorialStreams(long n) {
return LongStream.rangeClosed(1, n).reduce(1, (long x, long y) -> x * y);
}
public static void main(String[] args) {
System.out.println(Factorial_Java_8_2.factorialStreams(4));
}
}
OUTPUT :-
24
Interface Examples

package com.example.demo.java_8.Interface;
@FunctionalInterface
interface interfaceTest {
public void test();
}
@FunctionalInterface
interface interfaceTestadd {
public void test_add(int a, int b);
}
public class Java_8_Interface_test {
public static void main(String[] args) {
interfaceTest i = () -> System.out.println("Hello Interface");
i.test();
interfaceTestadd add_i = (a, b) -> System.out.println(a + b);
add_i.test_add(10, 89);
}
}
Output :- 
Hello Interface
99

==============================================================

Thread with run interface with Lambda Expression 

package com.example.demo.java_8.Runnable;
public class RunnableInterface {
public static void main(String[] args) {
Runnable r = () ->{
for(int i=0;i<10;i++) {
System.out.println("Child Thread - 1");
}
};
Thread t1 = new Thread(r);
t1.start();
for(int i=0;i<10;i++) {
System.out.println("Main Thread - 1");
}
}
}

OutPut :- 
Main Thread - 1
Child Thread - 1
Child Thread - 1
Child Thread - 1
Child Thread - 1
Child Thread - 1
Child Thread - 1
Child Thread - 1
Child Thread - 1
Child Thread - 1
Child Thread - 1
Main Thread - 1
Main Thread - 1
Main Thread - 1
Main Thread - 1
Main Thread - 1
Main Thread - 1
Main Thread - 1
Main Thread - 1
Main Thread - 1

===========================================================

Comparator with Lambada



package com.example.demo.java_8.comparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorTest_3 {

public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(0);
list.add(98);
list.add(4);
list.add(17);
list.add(12);
list.add(56);
list.add(11);
list.add(1);
list.add(0);
System.out.println(list);
Comparator<Integer> c = (I1,I2) -> (I1<I2)?-1 :(I1>I2)?1:0;
Collections.sort(list,c);
System.out.println(list);
                list.stream().forEach(System.out::println);
                List<Integer> l2 = list.stream().filter(i->i%2==0).collect(Collectors.toList());
System.out.println("------------------------------------");
l2.stream().forEach(System.out::println);

}

}
 OUTPUT :-

[1, 0, 98, 4, 17, 12, 56, 11, 1, 0]
[0, 0, 1, 1, 4, 11, 12, 17, 56, 98]
0
0
1
1
4
11
12
17
56
98
------------------------------------
0
0
4
12
56
98


Please make sure, you prepare well for the below programs. 1.Write a program to print employee details working in each department 2.Write a program to print employees count working in each department 3.Write a program to print active and inactive employees in the given collection 4.Write a program to print Max/Min employee salary from the given collection 5.Write a program to print the max salary of an employee from each department




 

package com.example.demo.java_8.Excercise;


public class Employee {
private int empId;
private String empName;
private int deptId;
private String status = "active";
private int salary;
public Employee(int empId, String empName, int deptId, String status, int salary) {
super();
this.empId = empId;
this.empName = empName;
this.deptId = deptId;
this.status = status;
this.salary = salary;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ", deptId=" + deptId + ", status=" + status
+ ", salary=" + salary + "]";
}
}




package com.example.demo.java_8.Excercise;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Java8Progress {
public static void main(String[] args) {
List<Employee> empList = new ArrayList<>();
empList.add(new Employee(101, "Siva", 101, "active", 2000));
empList.add(new Employee(102, "Reddy", 102, "active", 5000));
empList.add(new Employee(103, "Raju", 103, "inactive", 6000));
empList.add(new Employee(104, "Shivam", 104, "inactive", 4000));
empList.add(new Employee(105, "bob", 105, "active", 3500));
empList.add(new Employee(106, "Alice", 106, "inactive", 3500));
empList.add(new Employee(107, "Srinu", 107, "active", 3500));
Map<Integer, List<Employee>> empListBasedOnDept = empList.stream()
.collect(Collectors.groupingBy(Employee::getDeptId, Collectors.toList()));
empListBasedOnDept.entrySet().forEach(entry -> {
System.out.println(entry.getKey() + "----" + entry.getValue());
});
Map<Integer, Long> empListBasedOnDeptCount = empList.stream()
.collect(Collectors.groupingBy(Employee::getDeptId, Collectors.counting()));

empListBasedOnDeptCount.entrySet().forEach(entry ->{
System.out.println(entry.getKey()+ "---"+ entry.getValue());
});
}
}


-----------------------

OUTPUT :-


1----[Employee [empId=101, empName=Siva, deptId=1, status=active, salary=2000]]

2----[Employee [empId=102, empName=Reddy, deptId=2, status=active, salary=5000], Employee [empId=103, empName=Raju, deptId=2, status=inactive, salary=6000]]

3----[Employee [empId=104, empName=Shivam, deptId=3, status=inactive, salary=4000], Employee [empId=105, empName=bob, deptId=3, status=active, salary=3500]]

4----[Employee [empId=106, empName=Alice, deptId=4, status=inactive, salary=3500], Employee [empId=107, empName=Srinu, deptId=4, status=active, salary=3500]]

1---1

2---2

3---2

4---2


---------------------------------------------------------------------------------------------------------


https://javatechiess.wordpress.com/2021/06/02/cracking-the-coding-interview-java-streams-coding-questions/


https://github.com/javaTechiess/org/blob/main/src/javatechies/org/stream/EmployeeStreamDemo.java



Java 8 Stream #3 - Sorting with Comparator Example





1. What is functional Interface ?

A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods.



 Abstract Factory Pattern 

 

Abstract Factory Pattern says that just define an interface or abstract class for creating families of related (or dependent) objects but without specifying their concrete sub-classes. 

 

Abstract Factory lets a class returns a factory of classes. So, this is the reason that Abstract Factory Pattern is one level higher than the Factory Pattern. 

An Abstract Factory Pattern is also known as Kit. 

 

Advantage of Abstract Factory Pattern 

Abstract Factory Pattern isolates the client code from concrete (implementation) classes.

Usage of Abstract Factory Pattern 

When the system needs to be independent of how its object are created, composed, and represented.

Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern