Saturday, April 23, 2022

Programming -Java 8




 JAVA-8

hashCode

public int hashCode() {
return Objects.hash(department, id, name, salary);
}

public static int hash(Object... values) {

        return Arrays.hashCode(values);

    }

       
public static int hashCode(Object a[]) {
        if (a == null)
            return 0;
        int result = 1;
        for (Object element : a)
            result = 31 * result + (element == null ? 0 : element.hashCode());
        return result;
    }


Equals Methods
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EmployeeC other = (EmployeeC) obj;
return Objects.equals(department, other.department) && id == other.id &&                                                             Objects.equals(name, other.name)
&& salary == other.salary;
}
Factorial
package com.example.demo.java_8;
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


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


Comparator

1)

package com.example.demo.java_8.comparator;
import java.util.stream.LongStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Comapartor_Test_5 {
public static void main(String[] args) {
List<Integer> list_1 = new ArrayList<>();
list_1.add(3);
list_1.add(1);
list_1.add(23);
list_1.add(67);
list_1.add(31);
list_1.add(31);
list_1.add(19);
Comparator<Integer> c = (l1, l2) -> (l1 > l2) ? 1 : (l1 < l2) ? -1 : 0;
Collections.sort(list_1,c);

System.out.println(list_1);
}
}
OUTPUT :- 
[1, 3, 19, 23, 31, 31, 67]


------------------------------------------------------------------------------------------------------
2)

package com.example.demo.java_8.comparator;

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

public class Comapartor_Test_6 {

public static void main(String[] args) {

List<Integer> list_1 = Arrays.asList(23,45,6,78,1,23,45,67,80);

Comparator<Integer> c = (l1, l2) -> (l1 > l2) ? 1 : (l1 < l2) ? -1 : 0;
Collections.sort(list_1,c);
System.out.println(list_1);
}

}


OUTPUT :-
[1, 6, 23, 23, 45, 45, 67, 78, 80]

--------------------------------------------------------------------------------------------------------------
3)

package com.example.demo.java_8.comparator;

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

public class Comapartor_Test_7 {

public static void main(String[] args) {

List<String> list_1 = new ArrayList<>();
list_1.add("Aman");
list_1.add("Kunal");
list_1.add("Zeeshan");
list_1.add("Jayshree");
list_1.add("Nikunj");
list_1.add("Tiwari");
list_1.add("Dutta");
list_1.add("Pandey");
list_1.add("Sid");
list_1.add("Rahul");
list_1.add("Varun");
List<String> list_2 = list_1.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList());
System.out.println(list_2);
}

}
OUTPUT:-

[Aman, Dutta, Jayshree, Kunal, Nikunj, Pandey, Rahul, Sid, Tiwari, Varun, Zeeshan]

----------------------------------------------------------------------------------------------------------------
4)

package com.example.demo.java_8.comparator;

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

public class Comapartor_Test_7 {

public static void main(String[] args) {

List<String> list_1 = new ArrayList<>();
list_1.add("Aman");
list_1.add("Kunal");
list_1.add("Zeeshan");
list_1.add("Jayshree");
list_1.add("Nikunj");
list_1.add("Tiwari");
list_1.add("Dutta");
list_1.add("Pandey");
list_1.add("Sid");
list_1.add("Rahul");
list_1.add("Varun");
List<String> list_2 = list_1.stream().sorted((o1,o2)->o1.compareTo(o2)).collect(Collectors.toList());
System.out.println(list_2);
}

}


OUTPUT:-

[Aman, Dutta, Jayshree, Kunal, Nikunj, Pandey, Rahul, Sid, Tiwari, Varun, Zeeshan]
---------------------------------------------------------------------------------------------------------------
5)


package com.example.demo.java_8.comparator;

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

public class Comapartor_Test_7 {

public static void main(String[] args) {

List<String> list_1 = new ArrayList<>();
list_1.add("Aman");
list_1.add("Kunal");
list_1.add("Zeeshan");
list_1.add("Jayshree");
list_1.add("Nikunj");
list_1.add("Tiwari");
list_1.add("Dutta");
list_1.add("Pandey");
list_1.add("Sid");
list_1.add("Rahul");
list_1.add("Varun");
List<String> list_2 = list_1.stream().sorted().collect(Collectors.toList());
System.out.println(list_2);
}

}
 OUTPUT:-

[Aman, Dutta, Jayshree, Kunal, Nikunj, Pandey, Rahul, Sid, Tiwari, Varun, Zeeshan]


--------------------------------------------------------------------------------------------------------------------
6)


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

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

Comparator with Reverse Order

7)

package com.example.demo.java_8.comparator;

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

public class Comapartor_Test_8 {

public static void main(String[] args) {

List<String> list_1 = new ArrayList<>();
list_1.add("Aman");
list_1.add("Kunal");
list_1.add("Zeeshan");
list_1.add("Jayshree");
list_1.add("Nikunj");
list_1.add("Tiwari");
list_1.add("Dutta");
list_1.add("Pandey");
list_1.add("Sid");
list_1.add("Rahul");
list_1.add("Varun");
List<String> list_2 = list_1.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println(list_2);
}

}

OUTPUT :-

[Zeeshan, Varun, Tiwari, Sid, Rahul, Pandey, Nikunj, Kunal, Jayshree, Dutta, Aman]

--------------------------------------------------------------------------------------------------------------
8)

package com.example.demo.java_8.comparator;

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

public class Comapartor_Test_7_Reverse_Order {

public static void main(String[] args) {

List<String> list_1 = new ArrayList<>();
list_1.add("Aman");
list_1.add("Kunal");
list_1.add("Zeeshan");
list_1.add("Jayshree");
list_1.add("Nikunj");
list_1.add("Tiwari");
list_1.add("Dutta");
list_1.add("Pandey");
list_1.add("Sid");
list_1.add("Rahul");
list_1.add("Varun");
List<String> list_2 = list_1.stream().sorted((o1,o2)->o2.compareTo(o1)).collect(Collectors.toList());
System.out.println(list_2);
}

}
OUTPUT :-
[Zeeshan, Varun, Tiwari, Sid, Rahul, Pandey, Nikunj, Kunal, Jayshree, Dutta, Aman]
-----------------------------------------------------------------------------------------------------------------


Employee Comparator 

9)
package com.example.demo.java_8.Employee_comparatorC;

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

public class EomployeeComparator {

public static void main(String[] args) {

EmployeeC emp_1 = new EmployeeC(1, "Anil", 2000, "IT");
EmployeeC emp_2 = new EmployeeC(2, "Kunal", 3000, "IT");
EmployeeC emp_3 = new EmployeeC(3, "Pratibim", 3500, "IT");
EmployeeC emp_4 = new EmployeeC(4, "Harish", 2000, "HR");
EmployeeC emp_5 = new EmployeeC(5, "Himanshu", 2500, "HR");
EmployeeC emp_6 = new EmployeeC(6, "Manan", 2300, "HR");
EmployeeC emp_7 = new EmployeeC(7, "Vishnu", 2100, "Network");
EmployeeC emp_8 = new EmployeeC(8, "Shakti", 4300, "Network");
EmployeeC emp_9 = new EmployeeC(9, "Rakesh", 5500, "Network");
EmployeeC emp_10 = new EmployeeC(10, "Daya", 6000, "Manager");

List<EmployeeC> empList = new ArrayList<>();
empList.add(emp_1);
empList.add(emp_2);
empList.add(emp_3);
empList.add(emp_4);
empList.add(emp_5);
empList.add(emp_6);
empList.add(emp_7);
empList.add(emp_8);
empList.add(emp_9);
empList.add(emp_10);

List<EmployeeC> empSortedByNameList = empList.stream().sorted(Comparator.comparing(EmployeeC::getName))
.collect(Collectors.toList());
System.out.println(empSortedByNameList);
System.out.println("-----------------------------------------");
empSortedByNameList.forEach(System.out::println);
System.out.println("------------------------------------------------------");
System.out.println("----------------Reverse Order-------------------------");

List<EmployeeC> empSortedByNameReverseOrderList = empList.stream()
.sorted(Comparator.comparing(EmployeeC::getName).reversed()).collect(Collectors.toList());

empSortedByNameReverseOrderList.forEach(System.out::println);

}

}

OUTPUT :-

[EmployeeC [id=1, name=Anil, salary=2000, department=IT], EmployeeC [id=10, name=Daya, salary=6000, department=Manager], EmployeeC [id=4, name=Harish, salary=2000, department=HR], EmployeeC [id=5, name=Himanshu, salary=2500, department=HR], EmployeeC [id=2, name=Kunal, salary=3000, department=IT], EmployeeC [id=6, name=Manan, salary=2300, department=HR], EmployeeC [id=3, name=Pratibim, salary=3500, department=IT], EmployeeC [id=9, name=Rakesh, salary=5500, department=Network], EmployeeC [id=8, name=Shakti, salary=4300, department=Network], EmployeeC [id=7, name=Vishnu, salary=2100, department=Network]]
-----------------------------------------
EmployeeC [id=1, name=Anil, salary=2000, department=IT]
EmployeeC [id=10, name=Daya, salary=6000, department=Manager]
EmployeeC [id=4, name=Harish, salary=2000, department=HR]
EmployeeC [id=5, name=Himanshu, salary=2500, department=HR]
EmployeeC [id=2, name=Kunal, salary=3000, department=IT]
EmployeeC [id=6, name=Manan, salary=2300, department=HR]
EmployeeC [id=3, name=Pratibim, salary=3500, department=IT]
EmployeeC [id=9, name=Rakesh, salary=5500, department=Network]
EmployeeC [id=8, name=Shakti, salary=4300, department=Network]
EmployeeC [id=7, name=Vishnu, salary=2100, department=Network]
------------------------------------------------------
----------------Reverse Order-------------------------
EmployeeC [id=7, name=Vishnu, salary=2100, department=Network]
EmployeeC [id=8, name=Shakti, salary=4300, department=Network]
EmployeeC [id=9, name=Rakesh, salary=5500, department=Network]
EmployeeC [id=3, name=Pratibim, salary=3500, department=IT]
EmployeeC [id=6, name=Manan, salary=2300, department=HR]
EmployeeC [id=2, name=Kunal, salary=3000, department=IT]
EmployeeC [id=5, name=Himanshu, salary=2500, department=HR]
EmployeeC [id=4, name=Harish, salary=2000, department=HR]
EmployeeC [id=10, name=Daya, salary=6000, department=Manager]
EmployeeC [id=1, name=Anil, salary=2000, department=IT]

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

JustFilter
9)

package com.example.demo.java_8.Filter;

import java.util.Arrays;
import java.util.List;

public class JustFilter {

public static void main(String[] args) {
List<Integer> list = Arrays.asList(12,2,33,56,78);
list.stream().filter(x->x%2==0).forEach(System.out::println);

}

}

OUTPUT:-
12
2
56
78

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

Just MAP

10)

package com.example.demo.java_8.map;

import java.util.Arrays;
import java.util.List;

public class JustMap {

public static void main(String[] args) {

List<Integer> listOfMap = Arrays.asList(12,3,4,5,6);
listOfMap.stream().map(i-> i*i).forEach(System.out::println);
}

}

OUTPUT:-
144
9
16
25
36

====================================================================
FlatMap()


11)

package com.example.demo.java_8.map;

import java.util.List;
public class EmployeeForMap {
public int id;
public String name;
public List<String> cityWorkedUpon;
public EmployeeForMap(int id, String name, List<String> cityWorkedUpon) {
this.id = id;
this.name = name;
this.cityWorkedUpon = cityWorkedUpon;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getCityWorkedUpon() {
return cityWorkedUpon;
}
public void setCityWorkedUpon(List<String> cityWorkedUpon) {
this.cityWorkedUpon = cityWorkedUpon;
}
@Override
public String toString() {
return "EmployeeForMap [id=" + id + ", name=" + name + ", cityWorkedUpon=" + cityWorkedUpon + "]";
}
}


package com.example.demo.java_8.map;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class EmployeeForMapMainClass {
public static void main(String[] args) {
EmployeeForMap emp_1 = new EmployeeForMap(1, "KK", Arrays.asList("Pune", "Dubai", "Moscow", "Behrin"));
EmployeeForMap emp_2 = new EmployeeForMap(2, "Jaggi", Arrays.asList("Bglr", "Noida", "Bhopal", "Chandigarh"));
EmployeeForMap emp_3 = new EmployeeForMap(3, "Gaurav Shrivastva", Arrays.asList("Bglr", "Bhopal"));
EmployeeForMap emp_4 = new EmployeeForMap(4, "Ravi", Arrays.asList("Bglr", "Mumbai", "Amsterdam", "Rotardam"));
List<EmployeeForMap> listOfEmployee = Arrays.asList(emp_1, emp_2, emp_3, emp_4);
System.out.println("-----------------List of employee in Arrays form---------------------" + "\n");
System.out.println(listOfEmployee);
System.out.println("\n" + "-----------------Id's---------------------" + "\n");
System.out.println("\n" + "-----------------List of id from Lambda form---------------------" + "\n");
listOfEmployee.stream().map(x -> x.getId()).collect(Collectors.toList()).forEach(System.out::println);
System.out.println("\n" + "-----------------List of City from Lambda form---------------------" + "\n");
listOfEmployee.stream().map(x -> x.getCityWorkedUpon()).collect(Collectors.toList())
.forEach(System.out::println);

System.out.println("\n" + "-----------------List of city from FlatMap---------------------" + "\n");
Set<String> listOfCityOfEmployees = listOfEmployee.stream().flatMap(x -> x.getCityWorkedUpon().stream())
.collect(Collectors.toSet());

listOfCityOfEmployees.forEach(x -> System.out.print(x + " , "));
}
}

OUTPUT:-

-----------------List of employee in Arrays form---------------------
[EmployeeForMap [id=1, name=KK, cityWorkedUpon=[Pune, Dubai, Moscow, Behrin]], EmployeeForMap [id=2, name=Jaggi, cityWorkedUpon=[Bglr, Noida, Bhopal, Chandigarh]], EmployeeForMap [id=3, name=Gaurav Shrivastva, cityWorkedUpon=[Bglr, Bhopal]], EmployeeForMap [id=4, name=Ravi, cityWorkedUpon=[Bglr, Mumbai, Amsterdam, Rotardam]]]
-----------------Id's---------------------

-----------------List of id from Lambda form---------------------
1
2
3
4
-----------------List of City from Lambda form---------------------
[Pune, Dubai, Moscow, Behrin]
[Bglr, Noida, Bhopal, Chandigarh]
[Bglr, Bhopal]
[Bglr, Mumbai, Amsterdam, Rotardam]
-----------------List of city from FlatMap---------------------
Behrin , Bglr , Amsterdam , Chandigarh , Pune , Noida , Rotardam , Dubai , Moscow , Mumbai , Bhopal , 



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

Find City from flatMap

12)

package com.example.demo.PRACTICE;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FlatMapDemoWithEmpAndCity {
public static void main(String[] args) {
List<EmployeePracticeWithCity> empList = new ArrayList<EmployeePracticeWithCity>();
empList.add(new EmployeePracticeWithCity(101, "Ali", 2000.0, "Software",
Arrays.asList("Pune", "Mumbai", "Noida", "Delhi", "Bglr", "Bhopal", "Jamshedpur")));
empList.add(new EmployeePracticeWithCity(102, "Tiwari", 2300.0, "Software",
Arrays.asList("Pune", "Mumbai", "Bglr", "Bhopal", "Singrauli")));
empList.add(new EmployeePracticeWithCity(103, "Sidharth", 2350.0, "MS",
Arrays.asList("New York", "Bglr", "Bhopal", "Gorakhpur")));
empList.add(new EmployeePracticeWithCity(104, "Gaurav", 23450.0, "Software",
Arrays.asList("Pune", "Bglr", "Bhopal", "Baliya")));

List<String> city = empList.stream().flatMap(x->x.getCity().stream()).sorted().distinct().collect(Collectors.toList());
System.out.println(city);

}
}

OUTPUT:-

[Baliya, Bglr, Bhopal, Delhi, Gorakhpur, Jamshedpur, Mumbai, New York, Noida, Pune, Singrauli]


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


Compare salary and find out only list of name in reverse order

13)

package com.example.demo.PRACTICE;

/*Compare salary and find out only list of name in reverse order*/ 

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

public class FlatMapDemoWithEmpAndCity2 {

public static void main(String[] args) {

List<EmployeePracticeWithCity> empList = new ArrayList<EmployeePracticeWithCity>();
empList.add(new EmployeePracticeWithCity(101, "Ali", 2222000.0, "Software",
Arrays.asList("Pune", "Mumbai", "Noida", "Delhi", "Bglr", "Bhopal", "Jamshedpur")));
empList.add(new EmployeePracticeWithCity(102, "Tiwari", 2300.0, "Software",
Arrays.asList("Pune", "Mumbai", "Bglr", "Bhopal", "Singrauli")));

empList.add(new EmployeePracticeWithCity(103, "Sidharth", 2350.0, "MS",
Arrays.asList("New York", "Bglr", "Bhopal", "Gorakhpur")));
empList.add(new EmployeePracticeWithCity(104, "Gaurav", 23450.0, "Software",
Arrays.asList("Pune", "Bglr", "Bhopal", "Baliya")));

List<String> Names = empList.stream().sorted(Comparator.comparing(EmployeePracticeWithCity::getSalary).reversed())
.map(x -> x.getName()).collect(Collectors.toList());
System.out.println("\n----Compare salary and find out only list of name in reverse order-----\n");
Names.forEach(System.out::println);
}

}

OUTPUT:-


----Compare salary and find out only list of name in reverse order-----

Ali
Gaurav
Sidharth
Tiwari

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







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


14)

package com.example.demo.java_8.map;
import java.util.List;
import java.util.Objects;
public class EmployeeForMap2 {
public int id;
public String name;
public List<String> phoneNumber;
public EmployeeForMap2(int id, String name, List<String> phoneNumber) {
super();
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(List<String> phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Override
public String toString() {
return "EmployeeForMap2 [id=" + id + ", name=" + name + ", phoneNumber=" + phoneNumber + "]";
}
@Override
public int hashCode() {
return Objects.hash(id, name, phoneNumber);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EmployeeForMap2 other = (EmployeeForMap2) obj;
return id == other.id && Objects.equals(name, other.name) && Objects.equals(phoneNumber, other.phoneNumber);
}
}


package com.example.demo.java_8.map;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class EmployeeForMap2MainClass2 {
public static void main(String[] args) {
EmployeeForMap2 emp_1 = new EmployeeForMap2(1, "KK",
Arrays.asList("9004385690", "8004385680", "9884385690", "9224385622"));
EmployeeForMap2 emp_2 = new EmployeeForMap2(2, "Jaggi",
Arrays.asList("8004385681", "8004385682", "8774385680", "9994385680"));
EmployeeForMap2 emp_3 = new EmployeeForMap2(3, "Gaurav Shrivastva", Arrays.asList("9884385692", "9884385694"));
EmployeeForMap2 emp_4 = new EmployeeForMap2(4, "Ravi",
Arrays.asList("9224345622", "9884385696", "9884382222", "9884876694"));

List<EmployeeForMap2> listOfEmployee = Arrays.asList(emp_1, emp_2, emp_3, emp_4);
List<String> namesOfEmployee = listOfEmployee.stream().map(emp -> emp.getName()).collect(Collectors.toList());
System.out.println(namesOfEmployee);
namesOfEmployee.forEach(names -> System.out.print(names + " , "));
System.out.println("\n" + "-----------List of phone numbers in different arrays-------------" + "\n");

listOfEmployee.stream().map(phoneNmbers -> phoneNmbers.getPhoneNumber()).forEach(System.out::println);
System.out.println(
"\n" + "-----------List of phone numbers in same arrays with flatMap help-------------" + "\n");

List<String> listOfPhoneNumbersInSameArray = listOfEmployee.stream()
.flatMap(phoneNumbers -> phoneNumbers.getPhoneNumber().stream()).collect(Collectors.toList());
System.out.println(listOfPhoneNumbersInSameArray);

System.out.println("\n");
System.out.println("--------------------Duplicate number check--------------");

Map<String,Long> duplicateEliments = listOfPhoneNumbersInSameArray.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
duplicateEliments.entrySet().forEach(System.out::println);
}

}

OUTPUT :-

[KK, Jaggi, Gaurav Shrivastva, Ravi]
KK , Jaggi , Gaurav Shrivastva , Ravi , 
-----------List of phone numbers in different arrays-------------

[9004385690, 8004385680, 9884385690, 9224385622]
[8004385681, 8004385682, 8774385680, 9994385680]
[9884385692, 9884385694]
[9224345622, 9884385696, 9884382222, 9884876694]

-----------List of phone numbers in same arrays with flatMap help-------------

[9004385690, 8004385680, 9884385690, 9224385622, 8004385681, 8004385682, 8774385680, 9994385680, 9884385692, 9884385694, 9224345622, 9884385696, 9884382222, 9884876694]


--------------------Duplicate number check--------------
8774385680=1
9994385680=1
9224385622=1
8004385682=1
9884382222=1
8004385681=1
8004385680=1
9224345622=1
9884385694=1
9884385696=1
9884385690=1
9884385692=1
9004385690=1
9884876694=1

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

15)

package com.example.demo.java_8.FlatMap;
import java.util.List;
import java.util.stream.Stream;
public class FlateMapTest_2 {
public static void main(String[] args) {
List<Integer> list = List.of(2, 10, 15, 1, 9);
System.out.println("\n" + "--------simple Map--------" + "\n");
list.stream().map(i -> i + 10).forEach(System.out::println);
System.out.println("\n" + "--------flate Map--------" + "\n");
list.stream().flatMap(i -> Stream.of(i + 10, i * 2)).forEach(System.out::println);

System.out.println("\n" + "--------flate Map--------" + "\n");
}
}

OutPUT:-

--------simple Map--------

12
20
25
11
19
--------flate Map--------
12
4
20
20
25
30
11
2
19
18

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

16)

package com.example.demo.java_8.FlatMap;

import java.util.stream.IntStream;
import java.util.stream.Stream;
public class FlatMap_Test_3 {
public static void main(String[] args) {
int[] arr_1 = new int[] {1,2,4,6,7};
int[] arr_2 = new int[] {7,4,3,9};

System.out.println("\n"+"------All array in same list---------");
Stream.of(arr_1,arr_2).flatMapToInt(i->IntStream.of(i)).forEach(System.out::println);

                System.out.println("\n"+"------All array with distinct elements---------");
Stream.of(arr_1,arr_2).flatMapToInt(i>IntStream.of(i)).distinct().forEach(System.out::println);

}
}


OUTPUT:-

------All array in same list---------
1
2
4
6
7
7
4
3
9
------All array with distinct elements---------
1
2
4
6
7
3
9
------------------------------------------------------------------------------------------------
17)

package com.example.demo.java_8.FlatMap;

import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;

public class FlatMapDemo_2 {

public static void main(String[] args) {

int[] arr_1 = new int[] { 13, 22, 4, 6, 7 };
int[] arr_2 = new int[] { 7, 4, 3, 9 };

List<int[]> listOfInt = Arrays.asList(arr_1, arr_2);

listOfInt.stream().flatMapToInt(x -> IntStream.of(x)).distinct().sorted()
.forEach(x -> System.out.print(x + " "));

}

}
OUTPUT:-

3 4 6 7 9 13 22 

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

18)

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]

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

List With Arrays  (Very Important)

19)
package com.example.demo.java_8.FlatMap;

import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
public class FlatMapDemo_2 {
public static void main(String[] args) {
int[] arr_1 = new int[] { 13, 22, 4, 6, 7 };
int[] arr_2 = new int[] { 7, 4, 3, 9 };
List<int[]> listOfInt = Arrays.asList(arr_1, arr_2);
listOfInt.stream().flatMapToInt(x -> IntStream.of(x)).distinct().sorted()
.forEach(x -> System.out.print(x + " "));
}
}

OUTPUT:-

3 4 6 7 9 13 22 




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

COUNT 

20)

package com.example.demo.java_8.Count;

import java.util.Arrays;
import java.util.List;
public class CountTest {
public static void main(String[] args) {

List<Integer> list = Arrays.asList(1,23,4,45,56);
long totalNumbers = list.stream().count();
System.out.println(totalNumbers);
}
}

OUTPUT :-  5
===========================================================

SORTING

21)

package com.example.demo.java_8.Sort;

import java.util.Arrays;
import java.util.List;
public class SortingTest {
public static void main(String[] args) {

List<Integer> listForSort = Arrays.asList(12,3,4,55,6,7,99);
listForSort.stream().sorted().forEach(x->System.out.println(x));

}
}

OUTPUT :-
3
4
6
7
12
55
99

-----------------------------------------------------------------------------------------------
22)
package com.example.demo.java_8.Sort;

import java.util.Arrays;
import java.util.List;

public class WithComparator {

public static void main(String[] args) {
List<Integer> listForComparator = Arrays.asList(15,290,30);
System.out.println("Ascending order");
System.out.println("-----------------");
listForComparator.stream().sorted((i1,i2)-> i1.compareTo(i2)).forEach(x->System.out.println(x));
System.out.println("Reverse order");
System.out.println("-----------------");
listForComparator.stream().sorted((i1,i2)-> i2.compareTo(i1)).forEach(x->System.out.println(x));


}

}

OUTPUT :-

Ascending order
-----------------
15
30
290
Reverse order
-----------------
290
30
15

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




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

Min and Max


23)
package com.example.demo.java_8.Min_Max;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class MinMax_test {

public static void main(String[] args) {

Stream.of(12,3,4,56,78);
List<Integer> listForMinMax = Arrays.asList(13,56,2,89,566);
int min = listForMinMax.stream().min((i1,i2)-> i1.compareTo(i2)).get();
System.out.println("Minimum number : " + min);
int max = listForMinMax.stream().max((i1,i2)-> i1.compareTo(i2)).get();
System.out.println("Maximum number : " + max);
}

}

OUTPUT :-
Minimum number : 2
Maximum number : 566



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

toArray()

24)

package com.example.demo.java_8.toArray;

import java.util.Arrays;
import java.util.List;
public class ToArrayTest {
public static void main(String[] args) {
List<Integer> listForToArray = Arrays.asList(12, 89, 76, 4, 67);
System.out.println("Converting this Stream in Object Arrays");
Object arr[] = listForToArray.toArray();
for (Object a : arr) {
System.out.println(a);
}
}
}

OUTPUT:-
Converting this Stream in Object Arrays
12
89
76
4
67


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

Of()













25)

package com.example.demo.java_8.Of;

import java.util.stream.Stream;
public class OfTest {
public static void main(String[] args) {
Stream.of(3, 4, 67, "Ali", "news").forEach(x -> System.out.println(x));
System.out.println("===========================================");
String[] names = { "Kunal", "Rahim", "Badal", "Tiwari" };
Stream.of(names).forEach(x -> System.out.println(x));
}
}

OUTPUT :-

3
4
67
Ali
news
===========================================
Kunal
Rahim
Badal
Tiwari


----------------------------------------------------------------------------------------------------------------
26)
package com.example.demo.java_8.Of;

import java.util.Objects;


public class EmployeeOfTest {
public int id;
public String name;
public long salary;
public EmployeeOfTest(int id, String name, long salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
@Override
public String toString() {
return "EmployeeOfTest [id=" + id + ", name=" + name + ", salary=" + salary + "]";
}
@Override
public int hashCode() {
return Objects.hash(id, name, salary);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EmployeeOfTest other = (EmployeeOfTest) obj;
return id == other.id && Objects.equals(name, other.name) && salary == other.salary;
}
}



package com.example.demo.java_8.Of;

import java.util.Comparator;
import java.util.stream.Stream;
public class ofTestEmployee {
public static void main(String[] args) {

EmployeeOfTest emp_1 = new EmployeeOfTest(1,"Ali",400);
EmployeeOfTest emp_2 = new EmployeeOfTest(2,"Ali_2",350);
EmployeeOfTest emp_3 = new EmployeeOfTest(3,"Ali_3",200);
EmployeeOfTest emp_4 = new EmployeeOfTest(4,"Ali_4",440);

Stream.of(emp_1, emp_2,emp_3,emp_4).forEach(x->System.out.println(x));
System.out.println("-----------------Sortted-----------------------");

Stream.of(emp_1, emp_2,emp_3,emp_4).sorted(Comparator.comparingLong(EmployeeOfTest::getSalary)).forEach(x->System.out.println(x));


}
}

OUTPUT ;-


EmployeeOfTest [id=1, name=Ali, salary=400]
EmployeeOfTest [id=2, name=Ali_2, salary=350]
EmployeeOfTest [id=3, name=Ali_3, salary=200]
EmployeeOfTest [id=4, name=Ali_4, salary=440]
-----------------Sortted-----------------------
EmployeeOfTest [id=3, name=Ali_3, salary=200]
EmployeeOfTest [id=2, name=Ali_2, salary=350]
EmployeeOfTest [id=1, name=Ali, salary=400]
EmployeeOfTest [id=4, name=Ali_4, salary=440]

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



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

Parallel Stream























====================================================================
Duplicate Elements

27)

package com.example.demo.java_8.Duplicate_words;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
public class DuplicateInt {
public static void main(String[] args) {
List<Integer> listInt = Arrays.asList(1, 22, 33, 78, 33, 22, 98, 98, 98, 76, 76, 78,24,9);
Set<Integer> set = new HashSet<>();
System.out.println("\n"+"-----------Duplicate Elements------");
listInt.stream().filter(x -> !set.add(x)).collect(Collectors.toSet()).forEach(x -> System.out.println(x));
}
}


OUTPUT :-

-----------Duplicate Elements------
33
98
22
76
78
--------------------------------------------------------------------

Remove duplicate elements and store in map 

package com.example.demo;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/*1. Program : Find lowest and highest index of a specified number N in Sorted ArrayList.
eg. Input : [10, 12, 12, 12, 12, 50, 51, 89, 90, 1775, 1899] N=12 Output : [1, 4]*/

public class Remove_Duplicate {

static long finalcounter;

public static void main(String[] args) {

List<Integer> sortedList = Arrays.asList(10, 12, 12, 12, 12, 50, 51, 89, 89, 90, 90, 1775, 1899);

Set<Integer> set = new HashSet<>();

System.out.print("\n-------------------------------------------\n");
sortedList.stream().filter(x -> set.add(x)).map(x -> x).distinct().forEach(System.out::println);
}

}

OUTPUT:-

-------------------------------------------
10
12
50
51
89
90
1775
1899



Duplicate with Words

28)

package com.example.demo.java_8.Duplicate_words;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
public class DuplicateWords2 {
public static void main(String[] args) {

String str = "Hello world again Hello world again Hello world hello world";

List<String> listOfString = Arrays.asList(str.split(" "));
Map<String, Long> mapOfwordCount= listOfString.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));

System.out.println(mapOfwordCount);
}
}


OUTPUT :-

{world=4, Hello=3, again=2, hello=1}


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

29)

package com.example.demo.java_8.Duplicate_words;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Duplicate_word_stream {
public static void main(String[] args) {

List<String> list_of_words = Arrays.asList("Ali","Kunal","Ravi","Ali","Kunal","Ravi","Santosh","sahil");
Map<String, Long> mapOfDuplicate = list_of_words.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
mapOfDuplicate.entrySet().forEach(System.out::println);

System.out.println("\n-------Another way of showing rsult--------\n");

mapOfDuplicate.forEach((key,value)-> {
System.out.println(key+"---------"+value);
}
}

OUTPUT:-

Ravi=2
Kunal=2
sahil=1
Santosh=1
Ali=2

-------Another way of showing rsult--------

Ravi---------2
Kunal---------2
sahil---------1
Santosh---------1
Ali---------2


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

Duplicate with Numbers

30)

package com.example.demo.java_8.Duplicate_numbers;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Duplicate_numbers {
public static void main(String[] args) {

List<Integer> list_of_numbers = Arrays.asList(1,23,45,67,23,45,67,89,89,89,76);
Map<Integer, Long> countOfNumbers = list_of_numbers.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
countOfNumbers.entrySet().forEach(System.out::println);

System.out.println("------------Another Way to show Data--------------");

countOfNumbers.forEach((key,value)->
{
System.out.println(key+"------"+value);

});

}
}

OUTPUT :- 

1=1
67=2
23=2
89=3
76=1
45=2

------------Another Way to show Data--------------
1------1
67------2
23------2
89------3
76------1
45------2

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



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

Limit and Skip

31)

package com.example.demo.java_8.Limit;

import java.util.Arrays;
import java.util.List;
public class Limit_Skip_Test {
public static void main(String[] args) {

List<Integer> list = Arrays.asList(1,2,4,5,678,8,7,5,3,22);
System.out.println("\n"+"----------------Limit example-----------");
list.stream().limit(5).forEach(System.out::println);
System.out.println("\n"+"----------------Skip example-----------");
list.stream().skip(7).forEach(System.out::println);
}
}


OUTPUT ;-

----------------Limit example-----------

1
2
4
5
678
----------------Skip example-----------
5
3
22

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

Random Summary

IntStream Examples

32)

package com.example.demo.java_8.Random;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class RandomPrograms {
public static void main(String[] args) {


System.out.println("Sum of numbers from 1 to 5 \nTotal : "+IntStream.range(1, 5).sum()+"\n");

System.out.println("-----List of names sort and find first name---- ");

Stream.of("Kunal","Mahendra","Prateek","Sourabh","Podwal","Vikram","Ali").sorted().findFirst().ifPresent(System.out::println);
System.out.println("\n-----Names start with N print list---- \n");
String[] nameOfPersons = {"Pradeep","Sahil","Ritu","Natasha","Neha","Nikunj","Nousheen","Rupali","Reeti"};

Stream.of(nameOfPersons).filter(x->x.startsWith("N")).sorted().forEach(System.out::println);


System.out.println("\n-----(Same Result with Arrays.stream)Names start with R print list---- \n");

Arrays.stream(nameOfPersons).filter(x->x.startsWith("R")).sorted().forEach(System.out::println);

System.out.println("\n-----(Arrays.stream)Average---- \nAvergae : ");

Arrays.stream(new int[] {2,4,6,7,10}).map(x->x*x).average().ifPresent(System.out::print);

System.out.println("\n-----Lower case change and find and Print name with a---- \n");

List<String> people = Arrays.asList("Ankit","Anil","Amit","Rakes","Rajesh");

people.stream().map(x->x.toLowerCase()).filter(x->x.startsWith("a")).forEach(System.out::println);

System.out.println("\n-----Reduce Function---- \n");

double Total = Stream.of(7.3,1.8,8.9).reduce(0.0, (a,b) -> a+b);
System.out.println("Total : "+Total);



System.out.println("\n-----Static Summary---- \n");

IntSummaryStatistics summary = IntStream.of(1,56,78,2,5,9,34,56,45,99).summaryStatistics();
System.out.println(summary);
}
}

OUTPUT :- 

Sum of numbers from 1 to 5 
Total : 10

-----List of names sort and find first name---- 
Ali

-----Names start with N print list---- 

Natasha
Neha
Nikunj
Nousheen

-----(Same Result with Arrays.stream)Names start with R print list---- 

Reeti
Ritu
Rupali

-----(Arrays.stream)Average---- 
Avergae : 
41.0
-----Lower case change and find and Print name with a---- 

ankit
anil
amit

-----Reduce Function---- 

Total : 18.0

-----Static Summary---- 

IntSummaryStatistics{count=10, sum=385, min=1, average=38.500000, max=99}
------------------------------------------------------------------------------------------------------------

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

groupingBy
33)

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

--------------------------------------------------------------------------------------------------------------------
34)

package com.example.demo.java_8.grouping; public class EmployeeGrouping { public int id; public String name; public int age; public String gender; public String department; public int yearOfJoining; public double salary; public EmployeeGrouping(int id, String name, int age, String gender, String department, int yearOfJoining, double salary) { this.id = id; this.name = name; this.age = age; this.gender = gender; this.department = department; this.yearOfJoining = yearOfJoining; this.salary = salary; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public int getYearOfJoining() { return yearOfJoining; } public void setYearOfJoining(int yearOfJoining) { this.yearOfJoining = yearOfJoining; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } @Override public String toString() { return "EmployeeGrouping [id=" + id + ", name=" + name + ", age=" + age + ", gender=" + gender + ", department=" + department + ", yearOfJoining=" + yearOfJoining + ", salary=" + salary + "]"; } }




package com.example.demo.java_8.Functional_Interface;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.util.comparator.Comparators;

import com.example.demo.java_8.grouping.EmployeeGrouping;

public class EmployeeGroupingMain {
static List<EmployeeGrouping> EmployeeGroupingList = new ArrayList<EmployeeGrouping>();
public static void main(String[] args) {
EmployeeGroupingList.add(new EmployeeGrouping(111, "Jiya Brein", 32, "Female", "HR", 2011, 25000.0));
EmployeeGroupingList
.add(new EmployeeGrouping(122, "Paul Niksui", 25, "Male", "Sales And Marketing", 2015, 13500.0));
EmployeeGroupingList
.add(new EmployeeGrouping(133, "Martin Theron", 29, "Male", "Infrastructure", 2012, 18000.0));
EmployeeGroupingList
.add(new EmployeeGrouping(144, "Murali Gowda", 28, "Male", "Product Development", 2014, 32500.0));
EmployeeGroupingList.add(new EmployeeGrouping(155, "Nima Roy", 27, "Female", "HR", 2013, 22700.0));
EmployeeGroupingList
.add(new EmployeeGrouping(166, "Iqbal Hussain", 43, "Male", "Security And Transport", 2016, 10500.0));
EmployeeGroupingList
.add(new EmployeeGrouping(177, "Manu Sharma", 35, "Male", "Account And Finance", 2010, 27000.0));
EmployeeGroupingList
.add(new EmployeeGrouping(188, "Wang Liu", 31, "Male", "Product Development", 2015, 34500.0));
EmployeeGroupingList
.add(new EmployeeGrouping(199, "Amelia Zoe", 24, "Female", "Sales And Marketing", 2016, 11500.0));
EmployeeGroupingList
.add(new EmployeeGrouping(200, "Jaden Dough", 38, "Male", "Security And Transport", 2015, 11000.5));
EmployeeGroupingList
.add(new EmployeeGrouping(211, "Jasna Kaur", 27, "Female", "Infrastructure", 2014, 15700.0));
EmployeeGroupingList
.add(new EmployeeGrouping(222, "Nitin Joshi", 25, "Male", "Product Development", 2016, 28200.0));
EmployeeGroupingList
.add(new EmployeeGrouping(233, "Jyothi Reddy", 27, "Female", "Account And Finance", 2013, 21300.0));
EmployeeGroupingList
.add(new EmployeeGrouping(244, "Nicolus Den", 24, "Male", "Sales And Marketing", 2017, 10700.5));
EmployeeGroupingList.add(new EmployeeGrouping(255, "Ali Baig", 23, "Male", "Infrastructure", 2018, 12700.0));
EmployeeGroupingList
.add(new EmployeeGrouping(266, "Sanvi Pandey", 26, "Female", "Product Development", 2015, 28900.0));
EmployeeGroupingList
.add(new EmployeeGrouping(277, "Anuj Chettiar", 31, "Male", "Product Development", 2012, 35700.0));
// Query 1 : How many male and female employees are there in the organization?
method1();
System.out.println("\n");
// Query 2 : Print the name of all departments in the organization?
method2();
System.out.println("\n");
// Query 3 : What is the average age of male and female employees?
method3();
System.out.println("\n");
// Query 4 : Get the details of highest paid employee in the organization?
method4();
System.out.println("\n");
// Query 5 : Get the names of all employees who have joined after 2015?
method5();
System.out.println("\n");
// Query 6 : Count the number of employees in each department?
method6();
System.out.println("\n");
// Query 7 : What is the average salary of each department?
method7();
System.out.println("\n");
// Query 8 : Get the details of youngest male employee in the product
// development department?
method8();
System.out.println("\n");
// Query 9 : Who has the most working experience in the organization?
method9();
System.out.println("\n");
// Query 10 : How many male and female employees are there in the sales and
// marketing team?
method10();
System.out.println("\n");
// Query 11 : What is the average salary of male and female employees?
method11();
System.out.println("\n");
System.out.println("\n");
// Query 12 : List down the names of all employees in each department?
method12();
System.out.println("\n");
// Query 13 : What is the average salary and total salary of the whole
// organization?
method13();
System.out.println("\n");
// Query 14 : Separate the employees who are younger or equal to 25 years from
// those employees who are older than 25 years.
method14();
System.out.println("\n");
// Query 15 : Who is the oldest employee in the organization? What is his age
// and which department he belongs to?
method15();
}
private static void method1() {
System.out.println("Query 1 : How many male and female employees are there in the organization?");
Map<String, Long> noOfMaleAndFemaleEmployees = EmployeeGroupingList.stream()
.collect(Collectors.groupingBy(EmployeeGrouping::getGender, Collectors.counting()));
System.out.println(noOfMaleAndFemaleEmployees);
}
private static void method2() {
System.out.println("Query 2 : Print the name of all departments in the organization?");
EmployeeGroupingList.stream().map(EmployeeGrouping::getDepartment).distinct().forEach(System.out::println);
System.out.println("\n--------------2nd way of showing Department Data-----------------\n");
EmployeeGroupingList.stream().map(x -> x.getDepartment()).distinct().collect(Collectors.toList())
.forEach(System.out::println);
}
private static void method3() {
// Query 3 : What is the average age of male and female employees?
System.out.println("\n-------Query 3 : What is the average age of male and female employees?-----\n");
Map<String, Double> noOfMaleFemaleAverageAge = EmployeeGroupingList.stream().collect(Collectors
.groupingBy(EmployeeGrouping::getGender, Collectors.averagingDouble(EmployeeGrouping::getAge)));
System.out.println(noOfMaleFemaleAverageAge);
}
private static void method4() {
// Query 4 : Get the details of highest paid employee in the organization?
System.out.println("\n -----// Query 4 : Get the details of highest paid employee in the organization?-----\n");
Optional<EmployeeGrouping> highestPaidSalaryEmp = EmployeeGroupingList.stream()
.collect(Collectors.maxBy(Comparator.comparingDouble(EmployeeGrouping::getSalary)));
System.out.println(highestPaidSalaryEmp.get().getName());
}
private static void method5() {
// Query 5 : Get the names of all employees who have joined after 2015?
System.out.println("\n----// Query 5 : Get the names of all employees who have joined after 2015?---\n");
List<EmployeeGrouping> nameOfEmpWhoJoinAfter2015 = EmployeeGroupingList.stream()
.filter(x -> x.getYearOfJoining() > 2015).collect(Collectors.toList());
nameOfEmpWhoJoinAfter2015.forEach(System.out::println);
System.out.println(
"\n---- JUST FOR NAME Print, Another Method// Query 5 : Get the names of all employees who have joined after 2015?---\n");
EmployeeGroupingList.stream().filter(x -> x.getYearOfJoining() > 2015).map(EmployeeGrouping::getName)
.forEach(System.out::println);
}
private static void method6() {
// Query 6 : Count the number of employees in each department?
System.out.println("\n--------// Query 6 : Count the number of employees in each department?-----\n");
Map<String, Long> noOfEmployeesPerDepartment = EmployeeGroupingList.stream()
.collect(Collectors.groupingBy(EmployeeGrouping::getDepartment, Collectors.counting()));
noOfEmployeesPerDepartment.entrySet().forEach(System.out::println);
System.out.println(
"\n--------// Query 6 : Count the number of employees in each department?-----With entry and ---\n");
noOfEmployeesPerDepartment.entrySet().forEach(entry -> {
System.out.println(entry.getKey() + "----" + entry.getValue());
});
}
private static void method7() {
// Query 7 : What is the average salary of each department?
System.out.println("\n--------// Query 7 : What is the average salary of each department?-----\n");
Map<String, Double> avgSalaryOfEmployeesPerDepartment = EmployeeGroupingList.stream().collect(Collectors
.groupingBy(EmployeeGrouping::getDepartment, Collectors.averagingDouble(EmployeeGrouping::getSalary)));
avgSalaryOfEmployeesPerDepartment.entrySet().forEach(System.out::println);
}
private static void method8() {
// Query 8 : Get the details of youngest male employee in the product
// development department?
System.out.println("\n----// Query 8 : Get the details of youngest male employee in the product----\n");
EmployeeGroupingList.stream().filter(e -> e.getGender() == "Male" && e.getDepartment() == "product development")
.min(Comparator.comparing(EmployeeGrouping::getAge));
}
private static void method9() {
// Query 9 : Who has the most working experience in the organization?
System.out.println("\n -----Query 9 : Who has the most working experience in the organization?----\n");
EmployeeGrouping seniorEmployee = EmployeeGroupingList.stream()
.sorted(Comparator.comparingInt(EmployeeGrouping::getYearOfJoining)).findFirst().get();
System.out.println("----------Employee Details--------------");
System.out.println(seniorEmployee.getId() + "-----" + seniorEmployee.getName() + "----"
+ seniorEmployee.getYearOfJoining());
}
private static void method10() {
// Query 10 : How many male and female employees are there in the sales and
// marketing team?
System.out.println(
"\n------Query 10 : How many male and female employees are there in the sales and marketing team?-------\n");
Map<String, Long> noOfMasleAndFemaleInSsalesAndMarketing = EmployeeGroupingList.stream()
.filter(x -> x.getDepartment() == "Sales And Marketing")
.collect(Collectors.groupingBy(EmployeeGrouping::getGender, Collectors.counting()));
noOfMasleAndFemaleInSsalesAndMarketing.entrySet().forEach(System.out::println);
}
private static void method11() {
// Query 11 : What is the average salary of male and female employees?
System.out.println("\n-------Query 11 : What is the average salary of male and female employees?------\n");
Map<String, Double> averageSalaryOfMaleAndFemale = EmployeeGroupingList.stream().collect(Collectors
.groupingBy(EmployeeGrouping::getGender, Collectors.averagingDouble(EmployeeGrouping::getSalary)));
averageSalaryOfMaleAndFemale.entrySet().forEach(System.out::println);
}
private static void method12() {
// Query 12 : List down the names of all employees in each department?
System.out.println("\n----// Query 12 : List down the names of all employees in each department?---\n");
Map<String, List<EmployeeGrouping>> nameOfEmployeeAccordingToDep = EmployeeGroupingList.stream()
.collect(Collectors.groupingBy(EmployeeGrouping::getDepartment, Collectors.toList()));
nameOfEmployeeAccordingToDep.entrySet().forEach(System.out::println);
}
private static void method13() {
// Query 13 : What is the average salary and total salary of the whole
// organization?
System.out.println(
"\n----Query 13 : What is the average salary and total salary of the whole organization?-----\n");
DoubleSummaryStatistics employeeSalaryStatistics = EmployeeGroupingList.stream()
.collect(Collectors.summarizingDouble(EmployeeGrouping::getSalary));
System.out.println("Average Salary : " + employeeSalaryStatistics.getAverage());
System.out.println("Total Salary of all dept : " + employeeSalaryStatistics.getSum());
}
private static void method14() {
// Query 14 : Separate the employees who are younger or equal to 25 years from
// those employees who are older than 25 years.
List<EmployeeGrouping> listOfEmployeeGreaterThan25 = EmployeeGroupingList.stream().filter(x -> x.getAge() <= 25)
.collect(Collectors.toList());
listOfEmployeeGreaterThan25.forEach(System.out::println);
}
private static void method15() {
// Query 15 : Who is the oldest employee in the organization? What is his age
// and which department he belongs to?
Optional<EmployeeGrouping> seniorEmployee = EmployeeGroupingList.stream().sorted(Comparator.comparing(EmployeeGrouping::getAge).reversed()).findFirst();
System.out.println("Senior Employee in the Organization : "+seniorEmployee);
}
}


OUTPUT :-

Query 1 : How many male and female employees are there in the organization?
{Male=11, Female=6}


Query 2 : Print the name of all departments in the organization?
HR
Sales And Marketing
Infrastructure
Product Development
Security And Transport
Account And Finance

--------------2nd way of showing Department Data-----------------

HR
Sales And Marketing
Infrastructure
Product Development
Security And Transport
Account And Finance



-------Query 3 : What is the average age of male and female employees?-----

{Male=30.181818181818183, Female=27.166666666666668}



 -----// Query 4 : Get the details of highest paid employee in the organization?-----

Anuj Chettiar



----// Query 5 : Get the names of all employees who have joined after 2015?---

EmployeeGrouping [id=166, name=Iqbal Hussain, age=43, gender=Male, department=Security And Transport, yearOfJoining=2016, salary=10500.0]
EmployeeGrouping [id=199, name=Amelia Zoe, age=24, gender=Female, department=Sales And Marketing, yearOfJoining=2016, salary=11500.0]
EmployeeGrouping [id=222, name=Nitin Joshi, age=25, gender=Male, department=Product Development, yearOfJoining=2016, salary=28200.0]
EmployeeGrouping [id=244, name=Nicolus Den, age=24, gender=Male, department=Sales And Marketing, yearOfJoining=2017, salary=10700.5]
EmployeeGrouping [id=255, name=Ali Baig, age=23, gender=Male, department=Infrastructure, yearOfJoining=2018, salary=12700.0]

---- JUST FOR NAME Print, Another Method// Query 5 : Get the names of all employees who have joined after 2015?---

Iqbal Hussain
Amelia Zoe
Nitin Joshi
Nicolus Den
Ali Baig



--------// Query 6 : Count the number of employees in each department?-----

Product Development=5
Security And Transport=2
Sales And Marketing=3
Infrastructure=3
HR=2
Account And Finance=2

--------// Query 6 : Count the number of employees in each department?-----With entry and ---

Product Development----5
Security And Transport----2
Sales And Marketing----3
Infrastructure----3
HR----2
Account And Finance----2



--------// Query 7 : What is the average salary of each department?-----

Product Development=31960.0
Security And Transport=10750.25
Sales And Marketing=11900.166666666666
Infrastructure=15466.666666666666
HR=23850.0
Account And Finance=24150.0



----// Query 8 : Get the details of youngest male employee in the product----




 -----Query 9 : Who has the most working experience in the organization?----

----------Employee Details--------------
177-----Manu Sharma----2010



------Query 10 : How many male and female employees are there in the sales and marketing team?-------

Female=1
Male=2



-------Query 11 : What is the average salary of male and female employees?------

Male=21300.090909090908
Female=20850.0





----// Query 12 : List down the names of all employees in each department?---

Product Development=[EmployeeGrouping [id=144, name=Murali Gowda, age=28, gender=Male, department=Product Development, yearOfJoining=2014, salary=32500.0], EmployeeGrouping [id=188, name=Wang Liu, age=31, gender=Male, department=Product Development, yearOfJoining=2015, salary=34500.0], EmployeeGrouping [id=222, name=Nitin Joshi, age=25, gender=Male, department=Product Development, yearOfJoining=2016, salary=28200.0], EmployeeGrouping [id=266, name=Sanvi Pandey, age=26, gender=Female, department=Product Development, yearOfJoining=2015, salary=28900.0], EmployeeGrouping [id=277, name=Anuj Chettiar, age=31, gender=Male, department=Product Development, yearOfJoining=2012, salary=35700.0]]
Security And Transport=[EmployeeGrouping [id=166, name=Iqbal Hussain, age=43, gender=Male, department=Security And Transport, yearOfJoining=2016, salary=10500.0], EmployeeGrouping [id=200, name=Jaden Dough, age=38, gender=Male, department=Security And Transport, yearOfJoining=2015, salary=11000.5]]
Sales And Marketing=[EmployeeGrouping [id=122, name=Paul Niksui, age=25, gender=Male, department=Sales And Marketing, yearOfJoining=2015, salary=13500.0], EmployeeGrouping [id=199, name=Amelia Zoe, age=24, gender=Female, department=Sales And Marketing, yearOfJoining=2016, salary=11500.0], EmployeeGrouping [id=244, name=Nicolus Den, age=24, gender=Male, department=Sales And Marketing, yearOfJoining=2017, salary=10700.5]]
Infrastructure=[EmployeeGrouping [id=133, name=Martin Theron, age=29, gender=Male, department=Infrastructure, yearOfJoining=2012, salary=18000.0], EmployeeGrouping [id=211, name=Jasna Kaur, age=27, gender=Female, department=Infrastructure, yearOfJoining=2014, salary=15700.0], EmployeeGrouping [id=255, name=Ali Baig, age=23, gender=Male, department=Infrastructure, yearOfJoining=2018, salary=12700.0]]
HR=[EmployeeGrouping [id=111, name=Jiya Brein, age=32, gender=Female, department=HR, yearOfJoining=2011, salary=25000.0], EmployeeGrouping [id=155, name=Nima Roy, age=27, gender=Female, department=HR, yearOfJoining=2013, salary=22700.0]]
Account And Finance=[EmployeeGrouping [id=177, name=Manu Sharma, age=35, gender=Male, department=Account And Finance, yearOfJoining=2010, salary=27000.0], EmployeeGrouping [id=233, name=Jyothi Reddy, age=27, gender=Female, department=Account And Finance, yearOfJoining=2013, salary=21300.0]]



----Query 13 : What is the average salary and total salary of the whole organization?-----

Average Salary : 21141.235294117647
Total Salary of all dept : 359401.0


EmployeeGrouping [id=122, name=Paul Niksui, age=25, gender=Male, department=Sales And Marketing, yearOfJoining=2015, salary=13500.0]
EmployeeGrouping [id=199, name=Amelia Zoe, age=24, gender=Female, department=Sales And Marketing, yearOfJoining=2016, salary=11500.0]
EmployeeGrouping [id=222, name=Nitin Joshi, age=25, gender=Male, department=Product Development, yearOfJoining=2016, salary=28200.0]
EmployeeGrouping [id=244, name=Nicolus Den, age=24, gender=Male, department=Sales And Marketing, yearOfJoining=2017, salary=10700.5]
EmployeeGrouping [id=255, name=Ali Baig, age=23, gender=Male, department=Infrastructure, yearOfJoining=2018, salary=12700.0]


Senior Employee in the Organization : Optional[EmployeeGrouping [id=166, name=Iqbal Hussain, age=43, gender=Male, department=Security And Transport, yearOfJoining=2016, salary=10500.0]]

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

35)


package com.example.demo.java_8.Random;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class RandomPrograms {
public static void main(String[] args) {


System.out.println("Sum of numbers from 1 to 5 \nTotal : "+IntStream.range(1, 5).sum()+"\n");

System.out.println("-----List of names sort and find first name---- ");

Stream.of("Kunal","Mahendra","Prateek","Sourabh","Podwal","Vikram","Ali").sorted().findFirst().ifPresent(System.out::println);
System.out.println("\n-----Names start with N print list---- \n");
String[] nameOfPersons = {"Pradeep","Sahil","Ritu","Natasha","Neha","Nikunj","Nousheen","Rupali","Reeti"};

Stream.of(nameOfPersons).filter(x->x.startsWith("N")).sorted().forEach(System.out::println);

System.out.println("\n-----(Same Result with Arrays.stream)Names start with R print list---- \n");

Arrays.stream(nameOfPersons).filter(x->x.startsWith("R")).sorted().forEach(System.out::println);

System.out.println("\n-----(Arrays.stream)Average---- \nAvergae : ");

Arrays.stream(new int[] {2,4,6,7,10}).map(x->x*x).average().ifPresent(System.out::print);

System.out.println("\n-----Lower case change and find and Print name with a---- \n");

List<String> people = Arrays.asList("Ankit","Anil","Amit","Rakes","Rajesh");

people.stream().map(x->x.toLowerCase()).filter(x->x.startsWith("a")).forEach(System.out::println);

System.out.println("\n-----Reduce Function---- \n");

double Total = Stream.of(7.3,1.8,8.9).reduce(0.0, (a,b) -> a+b);
System.out.println("Total : "+Total);


System.out.println("\n-----Static Summary---- \n");

IntSummaryStatistics summary = IntStream.of(1,56,78,2,5,9,34,56,45,99).summaryStatistics();
System.out.println(summary);
}
}

OUTPUT:-

Sum of numbers from 1 to 5 
Total : 10

-----List of names sort and find first name---- 
Ali

-----Names start with N print list---- 

Natasha
Neha
Nikunj
Nousheen

-----(Same Result with Arrays.stream)Names start with R print list---- 

Reeti
Ritu
Rupali

-----(Arrays.stream)Average---- 
Avergae : 
41.0
-----Lower case change and find and Print name with a---- 

ankit
anil
amit

-----Reduce Function---- 

Total : 18.0

-----Static Summary---- 

IntSummaryStatistics{count=10, sum=385, min=1, average=38.500000, max=99}

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

A list of integer find start with 1

36)

package com.example.demo.PRACTICE;

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

public class FindStartWith_1 {

public static void main(String[] args) {

List<Integer> myList = Arrays.asList(10, 12, 3, 45, 67, 89);

List<String> myListName = Arrays.asList("Ravi", "Kunal", "Pradeep", "Lallan", "Rupesh", "Ranver", "Radhika",
"Rohan", "Ronney");
System.out.println("\n--A list of name find start with R--\n");
List<String> nameWithFilters = myListName.stream().filter(x -> x.startsWith("R")).collect(Collectors.toList());
nameWithFilters.forEach(System.out::println);
System.out.println("\n--A list of integer find start with 1--\n");
List<String> numberWithFilter = myList.stream().map(x -> x + "").filter(x -> x.startsWith("1"))
.collect(Collectors.toList());
numberWithFilter.forEach(System.out::println);
}

}
OUTPUT:-


--A list of name find start with R--

Ravi
Rupesh
Ranver
Radhika
Rohan
Ronney

--A list of integer find start with 1--

10
12


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

IntSummaryStatisticsDemo

37)

package com.example.demo.PRACTICE;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;

public class IntSummaryStatisticsDemo {

public static void main(String[] args) {

List<Integer> myList = Arrays.asList(10, 12, 3, 45, 67, 89);

IntSummaryStatistics summary_data_2 = new IntSummaryStatistics();
myList.stream().mapToInt(x -> x).forEach(summary_data_2);
System.out.println("Count: " + summary_data_2.getCount());
System.out.println("Average: " + summary_data_2.getAverage());
System.out.println("Max: " + summary_data_2.getMax());
System.out.println("min: " + summary_data_2.getMin());
System.out.println("Sum: " + summary_data_2.getSum());

                System.out.println("\n-----IntStream.of(4, 5, 6, 7)-----\n");
IntStream stream = IntStream.of(4, 5, 6, 7);

IntSummaryStatistics summary_data = stream.summaryStatistics();
System.out.println(summary_data);

}

}
OUTPUT :-
Count: 6
Average: 37.666666666666664
Max: 89
min: 3
Sum: 226

-----IntStream.of(4, 5, 6, 7)-----

IntSummaryStatistics{count=4, sum=22, min=4, average=5.500000, max=7}

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

Minimum and Maximum Salary 

38)

package com.example.demo.PRACTICE;

import java.util.List;

public class EmployeePracticeWithCity {

private int id;
private String name;
private double salary;
private String department;
public List<String> city;

public EmployeePracticeWithCity(int id, String name, double salary, String department, List<String> city) {
this.id = id;
this.name = name;
this.salary = salary;
this.department = department;
this.city = city;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

public List<String> getCity() {
return city;
}

public void setCity(List<String> city) {
this.city = city;
}

@Override
public String toString() {
return "EmployeePracticeWithCity [id=" + id + ", name=" + name + ", salary=" + salary + ", department="
+ department + ", city=" + city + "]";
}

}



package com.example.demo.PRACTICE;

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

public class MinAndMaxSalaryDemo {

public static void main(String[] args) {

List<EmployeePracticeWithCity> empList = new ArrayList<EmployeePracticeWithCity>();
empList.add(new EmployeePracticeWithCity(101, "Ali", 2222000.0, "Software",
Arrays.asList("Pune", "Mumbai", "Noida", "Delhi", "Bglr", "Bhopal", "Jamshedpur")));
empList.add(new EmployeePracticeWithCity(102, "Tiwari", 2300.0, "Software",
Arrays.asList("Pune", "Mumbai", "Bglr", "Bhopal", "Singrauli")));

empList.add(new EmployeePracticeWithCity(103, "Sidharth", 2350.0, "MS",
Arrays.asList("New York", "Bglr", "Bhopal", "Gorakhpur")));
empList.add(new EmployeePracticeWithCity(104, "Gaurav", 23450.0, "Software",
Arrays.asList("Pune", "Bglr", "Bhopal", "Baliya")));
EmployeePracticeWithCity minSalaryEmpDetails = empList.stream().min(Comparator.comparingDouble(EmployeePracticeWithCity::getSalary)).get();
System.out.println(minSalaryEmpDetails);
EmployeePracticeWithCity maxSalaryEmpDetails = empList.stream().max(Comparator.comparingDouble(EmployeePracticeWithCity::getSalary)).get();
System.out.println(maxSalaryEmpDetails);

Optional<EmployeePracticeWithCity> maxSalary = empList.stream().collect(Collectors.maxBy(Comparator.comparingDouble(EmployeePracticeWithCity::getSalary)));
System.out.println("\nUsing maxBy method for Max Salary : \n"+maxSalary);
Optional<EmployeePracticeWithCity> minSalary = empList.stream().collect(Collectors.minBy(Comparator.comparingDouble(EmployeePracticeWithCity::getSalary)));
System.out.println("\nUsing minBy method for Max Salary : \n"+minSalary);
EmployeePracticeWithCity maxSalaryUsingGetMethod = empList.stream().collect(Collectors.maxBy(Comparator.comparingDouble(EmployeePracticeWithCity::getSalary))).get();
System.out.println("\n Using maxBy method for Max Salary using getMethod without Optional : \n MaxSalary :\n"+maxSalaryUsingGetMethod);
EmployeePracticeWithCity minSalaryUsingGetMethod = empList.stream().collect(Collectors.minBy(Comparator.comparingDouble(EmployeePracticeWithCity::getSalary))).get();
System.out.println("\n Using maxBy method for Min Salary using getMethod without Optional : \n MinSalary :\n"+minSalaryUsingGetMethod);
}

}


OUTPUT:-

EmployeePracticeWithCity [id=102, name=Tiwari, salary=2300.0, department=Software, city=[Pune, Mumbai, Bglr, Bhopal, Singrauli]]
EmployeePracticeWithCity [id=101, name=Ali, salary=2222000.0, department=Software, city=[Pune, Mumbai, Noida, Delhi, Bglr, Bhopal, Jamshedpur]]

Using maxBy method for Max Salary : 
Optional[EmployeePracticeWithCity [id=101, name=Ali, salary=2222000.0, department=Software, city=[Pune, Mumbai, Noida, Delhi, Bglr, Bhopal, Jamshedpur]]]

Using minBy method for Max Salary : 
Optional[EmployeePracticeWithCity [id=102, name=Tiwari, salary=2300.0, department=Software, city=[Pune, Mumbai, Bglr, Bhopal, Singrauli]]]

 Using maxBy method for Max Salary using getMethod without Optional : 
 MaxSalary :
EmployeePracticeWithCity [id=101, name=Ali, salary=2222000.0, department=Software, city=[Pune, Mumbai, Noida, Delhi, Bglr, Bhopal, Jamshedpur]]

 Using maxBy method for Min Salary using getMethod without Optional : 
 MinSalary :
EmployeePracticeWithCity [id=102, name=Tiwari, salary=2300.0, department=Software, city=[Pune, Mumbai, Bglr, Bhopal, Singrauli]]


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

Max and Min value in the List of Integer

39)

package com.example.demo.PRACTICE;

import java.util.Arrays;
import java.util.List;

public class FindMaxNumber {

public static void main(String[] args) {

List<Integer> myList = Arrays.asList(10, 15, 8, 49, 25, 98, 98, 32, 15,8,8,8,8,98);
int maxValueInTheList = myList.stream().max(Integer::compare).get();
System.out.println("\nMaximum value  : "+maxValueInTheList);

int minValueInTheList = myList.stream().min(Integer::compare).get();

System.out.println("\nMinimum value  : "+minValueInTheList);

}

}

OUTPUT:-

Maximum value  : 98

Minimum value  : 8


----------------------------------------------------------------------------------------------
(39.5)

package com.example.java8;

import java.util.Arrays;
import java.util.List;

public class FindMaxNumber {

public static void main(String[] args) {
List<Integer> myList = Arrays.asList(10, 15, 8, 49, 25, 98, 98, 32, 15,8,8,8,8,98);
int maxValueInTheList = myList.stream().max(Integer::compare).get();
System.out.println("\nMaximum value  : "+maxValueInTheList);

int minValueInTheList = myList.stream().min(Integer::compare).get();

System.out.println("\nMinimum value  : "+minValueInTheList);
List<Double> myDoubleList = Arrays.asList(10.7, 15.2, 8.1, 49.6, 2.5, 9.8, 9.8, 3.2, 1.5,8.3,8.1,8.34,8.4,9.8);
double maxDValueInTheList = myDoubleList.stream().max(Double::compare).get();
System.out.println("\nMaximum dvalue  : "+maxDValueInTheList);

double minDValueInTheList = myDoubleList.stream().min(Double::compare).get();

System.out.println("\nMinimum dvalue  : "+minDValueInTheList);
}

}


OUTPUT:-


Maximum value  : 98

Minimum value  : 8

Maximum dvalue  : 49.6

Minimum dvalue  : 1.5



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

40)

Map's getOrDefault() function

package com.example.LeetCode_pepcode;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class MapWithKeyCount {

public static void main(String[] args) {

List<Integer> list = Arrays.asList(12, 1, 23, 45, 6, 12, 12, 1, 23);
Map<Integer, Integer> map = new HashMap<>();
TreeSet<Integer> duplicateEle = new TreeSet<>();

for (int ele : list) {

map.put(ele, map.getOrDefault(ele, 0) + 1);

}
for (int ele : list) {
if (map.get(ele) > 1) {
duplicateEle.add(ele);
}
}
TreeSet reverseTreeSet = (TreeSet) duplicateEle.descendingSet();
System.out.println(map);
System.out.println("----------------------------");
System.out.println(duplicateEle);
System.out.println("----------------------------");
System.out.println(reverseTreeSet);
}

}
  OUT : - 
{1=2, 6=1, 23=2, 12=3, 45=1}
----------------------------
[1, 12, 23]
----------------------------
[23, 12, 1]


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

41)

package com.example.LeetCode_javatechie;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class charArray {

public static void main(String[] args) {

String str = "I lovejavatechie";
Map<String, Long> map = Arrays.stream(str.split("")).
collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println(map);
String[] list = str.split("");
Map<String, Integer> map_2 = new HashMap<>();
for(String s : list) {
map_2.put(s, map_2.getOrDefault(s, 0)+1);
}
System.out.println("Map_2 :" + map_2);
}

}
 OUTPUT:-
{ =1, a=2, c=1, t=1, e=3, v=2, h=1, i=1, I=1, j=1, l=1, o=1}
Map_2 :{ =1, a=2, c=1, t=1, e=3, v=2, h=1, I=1, i=1, j=1, l=1, o=1}


------------------------------------------------------------------------------------------------------------------------
42)

package com.example.LeetCode_javatechie;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class DuplicateElements {

public static void main(String[] args) {

String str = "IlovejavaTechie";
List<String> duplicateElementlist = Arrays.stream(str.split(""))
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.entrySet().stream()
.filter(x-> x.getValue()>1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(duplicateElementlist);
System.out.println("----------------------------------");
List<String> uniqueElementlist = Arrays.stream(str.split(""))
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.entrySet().stream()
.filter(x-> x.getValue()==1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(uniqueElementlist);
}

}

OUTPUT:-

[a, e, v]
----------------------------------
[c, T, h, i, I, j, l, o]


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

Ternary Operator

Java ternary operator is the only conditional operator that takes three operands. It’s a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators. Although it follows the same algorithm as of if-else statement, the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.



(43)

package com.example.java8.Ternary_Operator;

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

public class TernaryTest {

public static void main(String[] args) {

int marks = 67 ;
String distinction = marks > 75 ? "Yes" : "No";
System.out.println("Hasd made distinction  : " + distinction);
System.out.println("---------------------------------");
List<String> selectNames = new ArrayList<>();
List<String> list = Arrays.asList("Ali","Kunal","Kabir","Raj","Abhijeet","Rakesh");
for(String names : list) {
names = names.length()>3 ? "Yes" : "No";
System.out.println(names);
}
System.out.println("---------------------------------");
for(String name : list) {
String bigNames = name.length()>3 ? String.valueOf(selectNames.add(name)) : "";
}
System.out.println(selectNames);
}

}
OUTPUT :-

Has made distinction  : No
---------------------------------
No
Yes
Yes
No
Yes
Yes
---------------------------------
[Kunal, Kabir, Abhijeet, Rakesh]

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

(44)

package com.example.java8;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class SumOfAllNumbers {

public static void main(String[] args) {

List<Integer> list = Arrays.asList(12,34,56,1,23,49,98);
Optional<Integer> sum = list.stream().reduce((a,b)-> a+b);
System.out.println("Sum of all Number :" +sum);
}

}
Output :-
Sum of all Number :Optional[273]

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

(45)

package com.example.java8;

import java.util.Arrays;
import java.util.List;

public class AverageByStream {

public static void main(String[] args) {

List<Integer> list = Arrays.asList(1,2,3,4,5);
double average = list.stream().mapToInt(x->x).average().getAsDouble();
System.out.println("Average of list : " + average);
}

}
OUTPU :-
Average of list : 3.0
---------------------------------------------------------------------------------------------------------
(46)

package com.example.java8;

import java.util.Arrays;
import java.util.List;

public class NumberSquareAverage {

public static void main(String[] args) {

List<Integer> list = Arrays.asList(1,10,20,30,15);
double average =list.stream().map(e->e*e)
.filter(e->e >100)
.mapToInt(e -> e)
.average().getAsDouble();
System.out.println("Square root of all element and sum and average of map : " + average);
}

}
OUTPUT :-
Square root of all element and sum and average of map : 508.3333333333333