package length;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class DemoArrays {
private static final String List = null;
public static void main(String[] args) {
// Print the stream
Stream<Integer>intStream = Stream.of(1, 2, 3);
intStream.forEach(e->System.out.println(e));
//intStream.forEach(System.out :: println); //Output 1 2 3
Stream<String> strString = Stream.of(“John”, “Doe”, “King”);
strString.forEach(System.out :: println);//Output: John Doe King
//Print from source
Collection<String> collection = Arrays.asList(“Jack”, “Perry”, “Wood”);
Stream<String> stream = collection.stream();
stream.forEach(System.out :: println); //Output: Jack Perry Wood
String[] strr= {“Hoog”, “Chang”, “Book”};
Stream<String> stream1=Arrays.stream(strr);
stream1.forEach(System.out :: println);//Output Hoog Chang Book
String[] st= {“Hoog”, “Chang”, “Book”};
Stream<String> stream2=Stream.of(st);
stream2.forEach(System.out :: println);//Output Hoog Chang Book
Integer[] arr= {6,7,8};
Stream<Integer> stream3 =Stream.of(arr);
stream3.forEach(System.out :: println);//Output 6 7 8
//Print from list
List<String> list = Arrays.asList(“a”, “b”);
Stream<String> stream4 = list.stream();
stream4.forEach(System.out::println);//Output a b
//Print from source
Set<String> set = new HashSet<>(list);
Stream<String> stream5 = collection.stream();
stream5.forEach(System.out::println);//Output: Jack Perry Wood
Stream<Integer> stream6 = Stream.of(3, 4, 6, 5, 1, 10);
stream6.filter(e->e%2==0).forEach(System.out :: println);//4 6 10
Stream<Integer> stream7 = Stream.of(3, 4, 6, 5, 1, 10);
stream7.filter(e->e%2==0).forEach(x->System.out.println(x));//4 6 10
//Multiply numbers
Stream<Integer> stream8 = Arrays.stream(arr);
stream8.map(a->a*a).forEach(System.out::println);//10 36 49 64
Stream<Integer> stream9 = Stream.of(3, 4, 6, 5, 1, 10);
stream9.limit(3).forEach(x->System.out.println(x));//3 4 6
Stream<Integer> stream10 = Stream.of(3, 4, 6, 5, 1, 10);//5 1 10
stream10.skip(3).forEach(System.out::println);
//Max and min values
Integer max=Stream.of(3, 4, 6, 5, 1, 10)
.max(Comparator.comparing(Integer::valueOf)).get();
System.out.println(“Print max no is: ” +max);//Print max no is: 10
Integer min=Stream.of(3, 4, 6, 5, 1, 10)
.min(Comparator.comparing(Integer::valueOf)).get();
System.out.println(“Print max no is: ” +min);//Print max no is: 1
//Counting the numbers
Stream<Integer>count=Stream.of(3, 4, 6, 5, 1, 10);
System.out.println(“The count is: ” +count.count());//The count is: 6
//Calculating average
Stream.of(3, 4, 6, 5, 1, 10)
.mapToInt(i->i).average().ifPresent(System.out::println);//4.833333333333333
//Average of positive numbers
Stream.of(3, 4, 6, 5, 1, 10).filter(i->i%2==0)
.mapToInt(i->i).average().ifPresent(System.out::println);//6.666666666666667
//Average of odd numbers
Stream.of(3, 4, 6, 5, 1, 10).filter(i->i%2!=0)
.mapToInt(i->i).average().ifPresent(System.out::println);//3.0
Stream.of(3, 4, 6, 5, 1, 10).filter(i->i%2!=0)
.mapToInt(i->i).average().ifPresent(e->System.out.println(“Average for odd nos is: ” +e));//Average for odd nos is: 3.0
//Count occurrence of a character
String str = “The Lord is good”;
//long count1 = str.chars().filter(e-> (char) e==’o’ || (char) e==’d’ )
// .count();
// System.out.println(“Characters appeared ” +count1 +” times”);//Characters appeared 5 times = 3 ooos and 2 ds
long count1 = str.chars().filter(e-> e==’o’ || e==’d’).count();
System.out.println(“Characters appeared ” +count1 +” times”);//Characters appeared 5 times = 3 ooos and 2 ds
Map<Character, Long>collect= str.codePoints().mapToObj(e->(char)e)
.collect(Collectors.groupingBy(e->e, Collectors.counting()));
System.out.println(collect);//{ =3, r=1, s=1, d=2, T=1, e=1, g=1, h=1, i=1, L=1, o=3}
Map<Character, Long>collect1= str.codePoints().mapToObj(e->(char)e)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(collect1);//{ =3, r=1, s=1, d=2, T=1, e=1, g=1, h=1, i=1, L=1, o=3}
//Find duplicate nos
List<Integer>dup=Arrays.asList(3, 3, 6, 4, 6, 5, 1, 10);
Set<Integer> i = new HashSet<>();
dup.stream().filter(e->!i.add(e)).forEach(System.out::println);// 3 6
List<String>dup1=Arrays.asList(“a”, “b”, “a”);
Set<String> s = new HashSet<>();
dup1.stream().filter(e->!s.add(e)).forEach(System.out::println);// a
String[] strrr = new String[] {“John”, “Doe”, “John”,”King”};
Stream.of(strrr)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream().filter(e->e.getValue()>1).map(e->e.getKey())
.forEach(System.out::println);// John
//Stream.Iterate – Infinite looping with applying limit – Stateful
Stream.iterate(0,e-> e+1).limit(3).forEach(System.out::println);// 0 1 2
Stream.iterate(0,e-> e+2).limit(3).forEach(System.out::println);// 0 2 4
//Stream.generate – Stateless
Stream.generate(()->(new Random()).nextInt(20)).limit(3).forEach(System.out::println);//11 16 2
//Short circuit operations
Stream.generate(()->(new Random()).nextInt(100))
.takeWhile(e->e<=50)
.forEach(System.out::println);//15 15 25
//Range v Range closed
//For loop
for(int x=0; x<3; x++) {
System.out.println(x);//0 1 2
}
//range()
int startInclusive =1;
int endExclusive =4;
int endInclusive =4;
IntStream range = IntStream.range(startInclusive, endExclusive);// 1 2 3
range.forEach(e->System.out.println(e));
//Range closed
// int startInclusive =1;
//int endInclusive =4;
IntStream rangeClosed = IntStream.rangeClosed(startInclusive, endInclusive);
rangeClosed.forEach(y->System.out.println(y));//1234
String str2 = “The Lord is our is shepard”;
List list2= Arrays.asList(str1.split(” “));
//Output: [The, Lord, is, our, is, shepard]
Map<String, Long>map=list1.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); System.out.println(map); //Output: {The=1, Lord=1, is=2, shepard=1, our=1} //Count the occurance of characters in the string String str3="Jesus"; Map<String, Long>map1=Arrays.stream(str.split("")).collect(Collectors .groupingBy(Function.identity(), Collectors.counting())); System.out.println(map); //{s=2, u=1, e=1, J=1}// long count1 = str.chars().filter(e-> e=='o' || e=='d').count(); // System.out.println("Characters appeared " +count1 +" times");//Characters appeared 5 time //Duplicate String List<String>l = Arrays.asList("Lord", "Lord", "John"); Set<String> w = new HashSet<>(); l.stream().filter(e->!w.add(e)).forEach(System.out::println);//Lord //Find duplicate integer Stream<Integer>s1=Stream.of(11, 13, 44, 11, 36, 36, 24); Set<Integer>h=new HashSet<>(); s1.filter(e->!h.add(e)).forEach(System.out::println);//11 36 //Find du0plicate string Stream<String>string=Stream.of("Lord", "Lord", "John"); Set<String>y=new HashSet<>(); string.filter(e->!y.add(e)).forEach(System.out::println);//Lord String a="Jesus"; List<String>b=Arrays.asList(a.split("")); Map<String, Long>mr= b.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); System.out.println(mr);//{s=2, u=1, e=1, J=1} //Sequancial pool IntStream.rangeClosed(0, 3).forEach(e->System.out.println(Thread.currentThread().getName() +':'+ e));//main:0 main:1 main:2 main:3 System.out.println("+++++++++++++++++++++"); //Parallel pool IntStream.rangeClosed(0, 3).parallel().forEach(e->System.out.println(Thread.currentThread().getName() +':'+ e));//main:2 main:3 main:1 main:0
}
}
package length;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class FilterDemo {
public static void main(String[] args) {
//Create product list
List<Product> list = new ArrayList<Product>();
list.add(new Product(1, “Flour”, 20));
list.add(new Product(3, “Sugar”, 30));
list.add(new Product(2, “Butter”, 10));
list.add(new Product(4, “Milk”, 5));
//Filter
list.stream().filter(p->p.price>10).forEach(System.out::println);
//Output Product [id=1, name=Flour, price=20.0]
// Product [id=3, name=Sugar, price=30.0]
System.out.println(“………….”);
list.stream().filter(product->product.name.startsWith(“M”))
.forEach(p->System.out.println(p));
//Output: Product [id=4, name=Milk, price=5.0]
System.out.println(“………….”);
list.stream()
.filter(p->p.price>20)
.filter(product->product.name.startsWith(“S”))
.forEach(e->System.out.println(e));
//Output: Product [id=3, name=Sugar, price=30.0]
System.out.println(“………….”);
//Collecting the list
List<Product>list1=
list.stream().filter(p->p.price<20).collect(Collectors.toList());
list1.forEach(System.out::println);
//Output: Product [id=2, name=Butter, price=10.0]
// Product [id=4, name=Milk, price=5.0]
}
}
class Product{
int id;
String name;
double price;
public Product(int id, String name, double price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return “Product [id=” + id + “, name=” + name + “, price=” + price + “]”;
}
package length;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MapDemo {
public static void main(String[] args) {
List<Car> list = new ArrayList<Car>();
list.add(new Car(“ML”, “Mercedes”, 50000, 10, “blue”));
list.add(new Car(“X6”, “BMW”, 60000, 20, “black”));
list.add(new Car(“GL-VX”, “Audi”, 55000, 12, “blue”));
list.add(new Car(“LX-3”, “Mercedes”, 90000, 7, “green”));
//filter
list.stream().filter(p->p.price>60000).forEach(System.out::println);
//Output: Car [model=LX-3, name=Mercedes, price=90000, quantity=7, color=green]
list.stream().filter(car->car.name.startsWith(“M”)).forEach(System.out::println);
//Output: Car [model=ML, name=Mercedes, price=50000, quantity=10, color=blue]
// Car [model=LX-3, name=Mercedes, price=90000, quantity=7, color=green]
//Map
list.stream().filter(car->car.quantity>10)
.map(car->car.model)
.forEach(e->System.out.println(“Model is: ” +e));
//Output: Model is: X6
// Model is: GL-VX
list.stream().filter(car->car.price>55000)
.map(car->car.model)
.forEach(e->System.out.println(“Model is: ” +e));
//Output: Model is: X6
// Model is: LX-3
//Collecting the list
List<String>carList=list.stream().filter(car->car.price<60000).map(car->car.model)
.collect(Collectors.toList());
carList.forEach(System.out::println);
//Output: ML
// GL-VX
// Collect all models
List<String>carList1=list.stream().map(p->p.model).collect(Collectors.toList());
carList1.forEach(System.out::println);
//Output: ML
//X6
//GL-VX
//LX-3
//Adding 5 cars to quantity less than 12
list.stream().filter(car->car.quantity<12).map(car->(car.quantity+5))
.forEach(e->System.out.println(“New quentity is: ” +e));
//Output:New quentity is: 15
// New quentity is: 12
//Get uniqu color of the cars
List<String>listColors=list.stream().map(car->car.color)
.collect(Collectors.toList());
listColors.forEach(System.out::println);
//Output: blue
// black
// blue
// green
List<String>listColors1=list.stream().map(car->car.color)
.distinct()
.collect(Collectors.toList());
listColors1.forEach(System.out::println);
//Output: blue
// black
// green
//Increae quantity of car by 10%
list.stream().filter(car->car.quantity>10)
.map(car->(car.quantity*1.1))
.forEach(System.out::println);//22.0
//13.200000000000001
}
}
class Car{
String model;
String name;
long price;
int quantity;
String color;
public Car(String model, String name, long price, int quantity, String color) {
super();
this.model = model;
this.name = name;
this.price = price;
this.quantity = quantity;
this.color = color;
}
@Override
public String toString() {
return “Car [model=” + model + “, name=” + name + “, price=” + price + “, quantity=” + quantity + “, color=”
+ color + “]”;
}
package length;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class EmployeeDemo {
public static void main(String[] args) {
List<Employee>employee = new ArrayList<Employee>();
employee.add(new Employee(“John”, 23, 50000));
employee.add(new Employee(“Kenny”, 25, 70000));
employee.add(new Employee(“Bruce”, 21, 35000));
employee.forEach(System.out::println);
//Output: Employee [name=John, age=23, salary=50000.0]
// Employee [name=Kenny, age=25, salary=70000.0]
// Employee [name=Bruce, age=21, salary=35000.0]
List<Employee>empList=employee.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName()))
.collect(Collectors.toList());
empList.forEach(System.out::println);
//Sorted by name
//Output: Employee [name=Bruce, age=21, salary=35000.0]
// Employee [name=John, age=23, salary=50000.0]
// Employee [name=Kenny, age=25, salary=70000.0]
//Sort by Age
List<Employee>empList1=employee.stream().sorted(Comparator.comparingInt(Employee::getAge))
.collect(Collectors.toList());
empList1.forEach(System.out::println);
//Sorted by age
//Output: Employee [name=Bruce, age=21, salary=35000.0]
// Employee [name=John, age=23, salary=50000.0]
// Employee [name=Kenny, age=25, salary=70000.0]
List<Employee>empList2=employee.stream().sorted(Comparator.comparingDouble(Employee::getSalary))
.collect(Collectors.toList());
empList2.forEach(System.out::println);
//Sorted by salary
//Output: Employee [name=Bruce, age=21, salary=35000.0]
// Employee [name=John, age=23, salary=50000.0]
// Employee [name=Kenny, age=25, salary=70000.0]
List<Employee>empLost3=employee.stream().sorted(Comparator.comparing(Employee::getName))
.collect(Collectors.toList());
empLost3.forEach(System.out::println);
//Sorted by name
//Output: Employee [name=Bruce, age=21, salary=35000.0]
// Employee [name=John, age=23, salary=50000.0]
// Employee [name=Kenny, age=25, salary=70000.0]
employee.stream().filter(e->e.getAge()>21)
.sorted(Comparator.comparingInt(Employee::getAge))
.forEach(System.out::println);
//Sort by age
//Output: Employee [name=John, age=23, salary=50000.0]
// Employee [name=Kenny, age=25, salary=70000.0]
}
}
class Employee{
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
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 double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return “Employee [name=” + name + “, age=” + age + “, salary=” + salary + “]”;
}
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;
public class EmployeeProgram {
public static void main(String[] args) { // TODO Auto-generated method stub List<Employee> list = new ArrayList<>(); list.add(new Employee(1, "John Doe", 111, "inactive", 25000)); list.add(new Employee(2, "Mark Bruce", 221, "active", 55000)); list.add(new Employee(3, "Gary King", 221, "active", 85000)); list.add(new Employee(4, "Jerry Khan", 111, "active", 80000)); list.add(new Employee(5, "Congo Box", 111, "active", 66000)); //List all employees by department list.stream().collect(Collectors.groupingBy(Employee::getDeptId, Collectors.toList())); Map<Integer, List<Employee>>listBasedOnDept=list.stream().collect(Collectors.groupingBy(Employee::getDeptId, Collectors.toList())); listBasedOnDept.entrySet().forEach(x -> { System.out.println(x.getKey() + "--" + x.getValue() ); }); /*System.out.println("List all employees by department ...."); 221--[Employee [empid=2, empName=Mark Bruce, deptId=221, status=active, salary=55000], Employee [empid=3, empName=Gary King, deptId=221, status=active, salary=85000]] 111--[Employee [empid=1, empName=John Doe, deptId=111, status=inactive, salary=25000], Employee [empid=4, empName=Jerry Khan, deptId=111, status=active, salary=80000], Employee [empid=5, empName=Congo Box, deptId=111, status=active, salary=66000]]*/ //Counting no. of departments and employees in each department Map<Integer, Long> empCountDept = list.stream().collect(Collectors.groupingBy(Employee::getDeptId, Collectors.counting())); empCountDept.entrySet().forEach(x-> { System.out.println(x.getKey() + "--" + x.getValue()); }); /*System.out.println("//Counting no. of departments and employees in each department ...."); 221--2 111--3*/ //Count active and inactive employees Long activeEmpCount = list.stream().filter(x -> "active".equals(x.getStatus())).count(); Long inactiveEmpCount = list.stream().filter(x -> "inactive".equals(x.getStatus())).count(); System.out.println("active emp count -- " + activeEmpCount); System.out.println("inactive emp count -- " + inactiveEmpCount); /*System.out.println("Count active and inactive employees ...."); active emp count -- 4 inactive emp count -- 1*/ System.out.println("Print maximum and minimum salaries ...."); //Print maximum and minimum salaries Optional<Employee> emp1 =list.stream().max(Comparator.comparing(Employee::getSalary)); Optional<Employee> emp2 =list.stream().min(Comparator.comparing(Employee::getSalary)); System.out.println(emp1); System.out.println(emp2); /* Print maximum and minimum salaries .... Optional[Employee [empid=3, empName=Gary King, deptId=221, status=active, salary=85000]] Optional[Employee [empid=1, empName=John Doe, deptId=111, status=inactive, salary=25000]]*/ System.out.println("List department and top salary earners ...."); //List department and top salary earners Map<Integer, Optional<Employee>> topSalaryEmpDept = list.stream().collect(Collectors.groupingBy(Employee::getDeptId, Collectors.reducing(BinaryOperator.maxBy(Comparator.comparing(Employee::getSalary))))); topSalaryEmpDept.entrySet().forEach(x-> { System.out.println("Dept " + x.getKey() + " topEmp " + x.getValue()); }); /* List department and top salary earners .... Dept 221 topEmp Optional[Employee [empid=3, empName=Gary King, deptId=221, status=active, salary=85000]] Dept 111 topEmp Optional[Employee [empid=4, empName=Jerry Khan, deptId=111, status=active, salary=80000]]*/}
}
package interface8;
interface Read {
void test();
}
public class FunctionalInterface {
public static void main(String[] args) {
//@Override
Read read=() -> System.out.println(“I can do all things!”);
read.test();//I can do all things!
}
}
interface Read {
void sum(int i);
}
public class FunctionalInterface {
public static void main(String[] args) {
//@Override
Read read=(i) -> System.out.println(“Print answer: ” +i);
read.sum(22); //Print answer: 22
}
}
package interface8;
interface Read {
int sum(int i, int j);
}
public class FunctionalInterface {
public static void main(String[] args) {
//@Override
Read read=(i,j) -> i+j; System.out.println(read.sum(22, 22));//44
}
}
package interface8;
interface Read {
int substract(int i, int j);
}
public class FunctionalInterface {
public static void main(String[] args) {
//@Override
Read read=(i,j) -> {
if(i<j) {
throw new RuntimeException(“msg”);
}else{
return (i-j);
}
};
System.out.println(read.substract(25, 15));//10
}
}
package java8Project;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerInt {
public static void main(String[] args) {
// TODO Auto-generated method stub
//@Override
Consumer<Integer>consumer=(t)-> {
System.out.println(“Output : ” +t);
};
consumer.accept(200); //Output : 200
List<Integer>list=Arrays.asList(2,6,3,9,7,5);
list.stream().forEach(consumer);
System.out.println(“=============”);/*
Output : 2
Output : 6
Output : 3
Output : 9
Output : 7
Output : 5*/
list.stream().forEach(t->System.out.println(“Output : ” +t));
/*=============
Output : 2
Output : 6
Output : 3
Output : 9
Output : 7
Output : 5*/
}
}
package java8Project;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
//public class PredicateInt implements Predicate<Integer>{
public class PredicateInt{
//@Override
/* public boolean test(Integer t) {
if(t%2==0) {
return true;
}else {
return false;
}
}*/
public static void main(String[] args) {
//Predicate<Integer>predicate=new PredicateInt();
//System.out.println(predicate.test(201));//false
System.out.println(“=============”);
Predicate<Integer> predicate1=(t)->(t%2!=0); {
System.out.println(predicate1.test(201));//true
Predicate<Integer> predicate=(t)->(t%2==0);
List<Integer>list=Arrays.asList(2,6,3,9,7,5);
list.stream().filter(predicate).forEach(t->System.out.println(“Output : ” +t));
// Output : 2
// Output : 6
list.stream().filter(t->t%2==0).forEach(t->System.out.println(“Output : ” +t));
// Output : 2
// Output : 6
}
}
}
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
//public class SupplierInt implements Supplier<String> {
public class SupplierInt {
//@Override
public String get() {
// TODO Auto-generated method stub
return “I can do all things”;
}
public static void main(String[] args) {
//Supplier<String>supplier=new SupplierInt();
//System.out.println(supplier.get());//I can do all things
//Lambda Expression
Supplier<String>supplier = ()-> {
// TODO Auto-generated method stub
return “I can do all things! Praise God!!”;
};
System.out.println(supplier.get()); //I can do all things! Praise God!!
Supplier<String>supplier1 = ()->”I define my destiny! Praise God!!”;
System.out.println(supplier1.get());//I define my destiny! Praise God!!
List<String>list=Arrays.asList(“Jack”, “Matt”, “Bank”);
System.out.println(list.stream().findAny().orElseGet(supplier1));//Jack
List<String>list1=Arrays.asList();
System.out.println(list1.stream().findAny().orElseGet(supplier));//I can do all things! Praise God!!
List<String>list3=Arrays.asList();
System.out.println(list3.stream().findAny().orElseGet(()->”I define my destiny! Praise God!!”));//I can do all things! Praise God!!
List<String>list2=Arrays.asList();
System.out.println(list2.stream().findAny().orElse(“I define my destiny! Praise God!!”));//I define my destiny! Praise God!!
}
}
package java8Project;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
//public class SupplierInt implements Supplier<String> {
public class SupplierInt {
//@Override
public String get() {
// TODO Auto-generated method stub
return “I can do all things”;
}
public static void main(String[] args) {
//Supplier<String>supplier=new SupplierInt();
//System.out.println(supplier.get());//I can do all things
//Lambda Expression
Supplier<String>supplier = ()-> {
// TODO Auto-generated method stub
return “I can do all things! Praise God!!”;
};
System.out.println(supplier.get()); //I can do all things! Praise God!!
Supplier<String>supplier1 = ()->”I define my destiny! Praise God!!”;
System.out.println(supplier1.get());//I define my destiny! Praise God!!
List<String>list=Arrays.asList(“Jack”, “Matt”, “Bank”);
System.out.println(list.stream().findAny().orElseGet(supplier1));//Jack
List<String>list1=Arrays.asList();
System.out.println(list1.stream().findAny().orElseGet(supplier));//I can do all things! Praise God!!
List<String>list3=Arrays.asList();
System.out.println(list3.stream().findAny().orElseGet(()->”I define my destiny! Praise God!!”));//I can do all things! Praise God!!
List<String>list2=Arrays.asList();
System.out.println(list2.stream().findAny().orElse(“I define my destiny! Praise God!!”));//I define my destiny! Praise God!!
List<String>list4=new ArrayList<>();
list4.add(“Ging”);
list4.add(“Baa”);
list4.add(“John”);
list4.add(“Doe”);
list4.add(“Johnson”);
for(String a:list4) {
System.out.println(a);
/*Ging
Baa
John
Doe*/
System.out.println(“==========”);
list4.stream().forEach(System.out::println);
/*Ging
Baa
John
Doe*/
System.out.println(“==========”);
System.out.println(“==========”);
Map<Integer, String>map=new HashMap<>();
map.put(1, “Max”);
map.put(3, “Sony”);
map.put(2, “Gabriel”);
map.forEach((key,value)->System.out.println(key + ” : ” + value));
/*1 : Max
2 : Gabriel
3 : Sony*/
System.out.println(“==========”);
map.entrySet().stream().forEach(e->System.out.println(e));
/*1=Max
2=Gabriel
3=Sony*/
System.out.println(“==========”);
//Internal working of the system
Consumer<String>consumer=(t)->System.out.println(t);
consumer.accept(“I can do all thing through Christ who strengthens me! Praise God!!”);
//I can do all thing through Christ who strengthens me! Praise God!!
for(String s: list4) {
System.out.println(s);
/*Ging
Baa
John
Doe*/
System.out.println(“==========”);
//Print name that start with
for(String a1:list4) {
if(a1.startsWith(“J”)) {
System.out.println(a1);
}
};
System.out.println(“==========”);
List<String>str=list4.stream().filter(e->e.startsWith(“J”)).collect(Collectors.toList());
str.forEach(t->System.out.println(t));//Johnson John
System.out.println(“==========”);
list4.stream().filter(o->o.startsWith(“B”)).forEach(System.out::println);//Baa
System.out.println(“==========”);
map.entrySet().stream().filter(e->e.getKey()%2==0).forEach(t->System.out.println(t));//2=Gabriel
}
}
}
}
package java8Project;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class Student {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return “Student [id=” + id + “, name=” + name + “, age=” + age + “]”;
}
public static void main(String[] args) {
List<Student>student=new ArrayList<>();
student.add(new Student(11, “John”, 19));
student.add(new Student(05, “Bank”, 18));
student.add(new Student(22, “Jacob”, 26));
student.add(new Student(17, “Doe”, 29));
//print record
student.forEach(System.out::println);
/*Student [id=11, name=John, age=19]
Student [id=5, name=John, age=18]
Student [id=22, name=John, age=26]
Student [id=17, name=John, age=29]*/
System.out.println(“=======================”);
//Sort record by name
List<Student>sName=student.stream().sorted((e1,e2)->e1.name.compareTo(e2.name))
.collect(Collectors.toList());
sName.forEach(System.out::println);
System.out.println(“=======================”);
List<Student>sName1=student.stream().sorted(Comparator.comparingInt(Student::getAge))
.collect(Collectors.toList());
sName1.forEach(System.out::println);
System.out.println(“=======================”);
List<Student>sName2=student.stream().sorted(Comparator.comparingInt(Student::getId))
.collect(Collectors.toList());
sName2.forEach(System.out::println);
System.out.println(“=======================”);
Optional stdId=student.stream().max(Comparator.comparing(Student::getAge));
System.out.println(“The oldest student is ” +stdId);
System.out.println(“=======================”);
List<Student>stu=student.stream().sorted((e1,e2)->e2.getName().compareTo(e1
.getName()))
.collect(Collectors.toList());
stu.forEach(System.out::println);
}
}
package java8Project;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Employee {
private int id;
private String name;
private String deptId;
private long salary;
public Employee(int id, String name, String deptId, long salary) {
super();
this.id = id;
this.name = name;
this.deptId = deptId;
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 String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
@Override
public String toString() {
return “Employee [id=” + id + “, name=” + name + “, deptId=” + deptId + “, salary=” + salary + “]”;
}
public static void main(String[] args) {
List<Employee>emp=new ArrayList<>();
emp.add(new Employee(120,”John”,”IT”,90000));
emp.add(new Employee(101,”Doe”,”Admin”,53000));
emp.add(new Employee(110,”Johnson”,”Finance”,65000));
emp.add(new Employee(115,”Bank”,”IT”,55000));
//List all employee
emp.stream().forEach(System.out::println);
/*Employee [id=120, name=John, deptId=IT, salary=90000]
Employee [id=101, name=Doe, deptId=Admin, salary=53000]
Employee [id=110, name=Johnson, deptId=Finance, salary=65000]
Employee [id=115, name=Bank, deptId=IT, salary=55000]*/
System.out.println(“===========”);
//List employee with salary greater than 55000
List<Employee>taxElegible=emp.stream().filter(e->e.getSalary()>55000)
.collect(Collectors.toList());
taxElegible.forEach(System.out::println);
/*Employee [id=120, name=John, deptId=IT, salary=90000]
Employee [id=110, name=Johnson, deptId=Finance, salary=65000]*/
List<Integer>num=new ArrayList<>();
num.add(14);
num.add(10);
num.add(19);
num.add(13);
Collections.sort(num);
System.out.println(num);//[10, 13, 14, 19] Ascending
System.out.println(“===========”);
Collections.reverse(num);
System.out.println(num);//[19, 14, 13, 10]Descending
System.out.println(“===========”);
num.stream().sorted().forEach(System.out::println);
/*10
13
14
19*/
System.out.println(“===========”);
num.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
/*19
14
13
10*/
System.out.println(“===========”);//Salary ascending order
emp.stream().sorted(Comparator.comparingLong(Employee::getSalary))
.forEach(System.out::println);
/*Employee [id=101, name=Doe, deptId=Admin, salary=53000]
Employee [id=115, name=Bank, deptId=IT, salary=55000]
Employee [id=110, name=Johnson, deptId=Finance, salary=65000]
Employee [id=120, name=John, deptId=IT, salary=90000]*/
System.out.println(“===========”);//Name ascending order
emp.stream().sorted((o1,o2)->o1.getName().compareTo(o2.getName()))
.forEach(System.out::println);
/*Employee [id=115, name=Bank, deptId=IT, salary=55000]
Employee [id=101, name=Doe, deptId=Admin, salary=53000]
Employee [id=120, name=John, deptId=IT, salary=90000]
Employee [id=110, name=Johnson, deptId=Finance, salary=65000]*/
System.out.println(“===========”);//Name ascending order
emp.stream().sorted(Comparator.comparing(Employee::getDeptId))
.forEach(System.out::println);
}
}
//If Statement
int a=20;
int b=15;
if(a>b) {
System.out.println(“A is greater!”);
}else {
System.out.println(“b is greater than a!”);
}
System.out.println(a==b);
for(int i=0;i<5;i++) {
System.out.println(i + “:” + “I can do all things!”);
}
/*0:I can do all things!
1:I can do all things!
2:I can do all things!
3:I can do all things!
4:I can do all things!*/
for(int i=0;i<5;i++) {
if(i==3) {
break;
}
System.out.println(i + “:” + “I can do all things!”);
}
for(int i=0;i<5;i++) {
if(i==3) {
continue;
}
System.out.println(i + “:” + “I can do all things!”);
}
int i=0;
while(i<4) {
System.out.println(i);
i++;
}
int z=0;
do {
System.out.println(z + “:” + ” I am the greatest!”);
z++;
}
while(z<5);
int i=0;
do {
System.out.println(i + “:” + ” I can do all things!”);
i++;
}
while(i<5);
//Arrays
String[] str= {“John”, “Bank”, “Joe”};
for(String y:str) {
System.out.println(y);
System.out.println(str[2]);
}
for(int j=0;j<str.length;j++) {
System.out.println(str[j]);
}
int[] arr= {1,3,5,8,6};
for(int x=0;x<arr.length;x++){
System.out.println(arr[x]);
}
}
}
List<Employee>emp=new ArrayList<>();
emp.add(new Employee(120,”John”,”IT”,90000));
emp.add(new Employee(101,”Doe”,”Admin”,53000));
emp.add(new Employee(110,”Johnson”,”Finance”,65000));
emp.add(new Employee(115,”Bank”,”IT”,55000));
//List all employee
emp.stream().forEach(System.out::println);
/*Employee [id=120, name=John, deptId=IT, salary=90000]
Employee [id=101, name=Doe, deptId=Admin, salary=53000]
Employee [id=110, name=Johnson, deptId=Finance, salary=65000]
Employee [id=115, name=Bank, deptId=IT, salary=55000]*/
System.out.println(“===========”);
//List employee with salary greater than 55000
List<Employee>taxElegible=emp.stream().filter(e->e.getSalary()>55000)
.collect(Collectors.toList());
taxElegible.forEach(System.out::println);
/*Employee [id=120, name=John, deptId=IT, salary=90000]
Employee [id=110, name=Johnson, deptId=Finance, salary=65000]*/
List<Integer>num=new ArrayList<>();
num.add(14);
num.add(10);
num.add(19);
num.add(13);
Collections.sort(num);
System.out.println(num);//[10, 13, 14, 19] Ascending
System.out.println(“===========”);
Collections.reverse(num);
System.out.println(num);//[19, 14, 13, 10]Descending
System.out.println(“===========”);
num.stream().sorted().forEach(System.out::println);
/*10
13
14
19*/
System.out.println(“===========”);
num.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
/*19
14
13
10*/
System.out.println(“===========”);//Salary ascending order
emp.stream().sorted(Comparator.comparingLong(Employee::getSalary))
.forEach(System.out::println);
/*Employee [id=101, name=Doe, deptId=Admin, salary=53000]
Employee [id=115, name=Bank, deptId=IT, salary=55000]
Employee [id=110, name=Johnson, deptId=Finance, salary=65000]
Employee [id=120, name=John, deptId=IT, salary=90000]*/
System.out.println(“===========”);//Name ascending order
emp.stream().sorted((o1,o2)->o1.getName().compareTo(o2.getName()))
.forEach(System.out::println);
/*Employee [id=115, name=Bank, deptId=IT, salary=55000]
Employee [id=101, name=Doe, deptId=Admin, salary=53000]
Employee [id=120, name=John, deptId=IT, salary=90000]
Employee [id=110, name=Johnson, deptId=Finance, salary=65000]*/
System.out.println(“===========”);//Name ascending order
emp.stream().sorted(Comparator.comparing(Employee::getDeptId))
.forEach(System.out::println);
int age=67;
if(age < 18) {
System.out.println(“Cannot vote”);
} else if(age==18 || age <=66){
System.out.println(“You can do anything!”);
}else
{
System.out.println(“You are limited!”);
}
}
}
// Properties
String name= “Conqueror”;
String nationality = “British”;
public static void main(String[] args) {
Student obj = new Student(); //New student
Student obj1 = new Student(); // New nationality
System.out.println(obj.name);//Conqueror
System.out.println(obj.nationality);//British
}
Java Maths Class
System.out.println(Math.max(3, 6));//6
System.out.println(Math.sqrt(144));//12
Absolute positive value
System.out.println(Math.abs(-7.7));//7.7
System.out.println(Math.random());//0.512200093093726
int randomValue = (int)(Math.random() * 100);
System.out.println(randomValue);//74