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
=====================================================================
Employee Comparator
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 + " , "));
}
}
-----------------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)
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);
}
}
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("--------------------Duplicate number check--------------");
duplicateEliments.entrySet().forEach(System.out::println);
}
--------------------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
-------------------------------------------------------------------------------------------------
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");
}
}
12
20
25
11
19
--------flate Map--------
12
4
20
20
25
30
11
2
19
18
------------------------------------------------------------------
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);
Stream.of(arr_1,arr_2).flatMapToInt(i>IntStream.of(i)).distinct().forEach(System.out::println);
}
}
------------------------------------------------------------------------------------------------
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]
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 + " "));
}
}
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);
}
}
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));
}
}
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);
}
}
}
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));
}
}
3
4
67
Ali
news
===========================================
Kunal
Rahim
Badal
Tiwari
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=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]
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 :-
33
98
22
76
78
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}
----------------------------------------------------------------------------------------------------------
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);
mapOfDuplicate.forEach((key,value)-> {
System.out.println(key+"---------"+value);
}
-------------------------------------------------------------------------------------------------------------
Duplicate with Numbers
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 :-
67=2
23=2
89=3
76=1
45=2
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-----------
2
4
5
678
----------------Skip example-----------
5
3
22
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);
}
}
package com.example.demo.java_8.Excercise;
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.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
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);
}
}
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.