Commit ba73c177 authored by Abdul Mujeeb Mohammed's avatar Abdul Mujeeb Mohammed

first commit

parents
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="Completereference" />
</profile>
</annotationProcessing>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Completereference</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
\ No newline at end of file
package lamda.consumer;
import lamda.pojo.Employee;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* Consumer gives input argument to any operation
* doesn't return anything
*/
public class ConsumerExample {
public static void main(String[] args) {
//Basic start
Consumer<Integer> data = System.out::println;
data.accept(123);
//Employee List
List<Employee> empList = new ArrayList<>();
empList.add(new Employee(123, "ashoke", "manager", 10001.00));
empList.add(new Employee(424, "bharat", "lead", 10002.00));
empList.add(new Employee(621, "chandu", "director", 10005.00));
empList.add(new Employee(93, "danish", "developer", 10006.00));
empList.add(new Employee(448, "eenadu", "developer", 10001.00));
Consumer<Employee> names = n-> System.out.println(n.getName());
//getNames from employee
empList.forEach(names);
//get complete List
empList.forEach(System.out::println);
Consumer<String> lower = s -> System.out.println(s.toLowerCase());
Consumer<String> upper = s -> System.out.println(s.toUpperCase());
Consumer<String> getChar = s -> System.out.println(s.charAt(2));
//Consumer<Integer> intData = s->System.out.println(s+"123"); // cannot convert String to int
/**
* andThen
* it will print all the above condition given
*/
Consumer<String> output = lower.andThen(upper).andThen(getChar); // performing operation
output.accept("ApplicaTion"); // input
/**
* BiConsumer
* It takes 2 parameters
*/
BiConsumer<String,String> x = (a,b)-> System.out.println("Consuming two parameters.. : "+a+"---"+b);
x.accept("Hello", "java");
}
}
package lamda.first;
import lamda.userdefined.functional.interfaces.*;
public class Demo implements MyNumber, NumericTest, NumericTest2 {
public static void main(String[] args) {
//Lamda for fixed number
MyNumber num = () -> 123.4;
System.out.println("Fixed value is "+num.getValue());
num = () -> Math.random();
System.out.println("Random number is "+ num.getValue());
System.out.println("Another random number is "+ num.getValue());
//num = ()->"Hello Lamda"; // error
// Without lamda
Demo demo = new Demo();
System.out.println(demo.getValue());
//Numeric test , 2nd interface
//lamda expression
NumericTest isEven;
isEven = i -> i%2 == 0 ;
if(isEven.test(10))
System.out.println("10 is an even number");
if(!isEven.test(9))
System.out.println("9 is not an even number");
//chek for non negetive numbers
NumericTest nonNeg;
nonNeg = (i)->i>=0;
if(nonNeg.test(3))
System.out.println("3 is non negetive number");
if(!nonNeg.test(-2))
System.out.println("-2 is a negetive number");
//Numeric Test 3rd interface
NumericTest2 num2;
num2 = (x,y) -> x>y;
if(!num2.test(2,3))
System.out.println("2 is not a greater number ");
num2 = (x,y)-> x%y == 0;
if(num2.test(10,2))
System.out.println("Given number is a factorial");
if(!num2.test(10,3))
System.out.println("Given numbers are not Factorial");
//BLOCK LAMDA DEMO
NumericFunc numF ;
numF = x -> {
int result = 1;
for(int i=1; i<=x ; i++){
result = i* result;
}
return result;
};
System.out.println("Factorial of 3 is "+numF.func(3));
System.out.println("Factorial of 6 is "+numF.func(6));
// Reverse a string character
StringFunc strF;
strF = s->{
String result = "";
for(int i = s.length()-1; i>=0 ;i--){
result = result+s.charAt(i);
}
return result;
};
System.out.println(strF.func("flag"));
//GENERIC In Functional Interface
SomeFunc<String> some = s->{
String result = "";
for(int i = s.length()-1; i>=0 ;i--){
result = result+s.charAt(i);
}
return result;
};
System.out.println(some.somFun("stone"));
SomeFunc<Integer> someNum = x -> {
int result = 1;
for(int i=1; i<=x ; i++){
result = i* result;
}
return result;
};
System.out.println("Factorial of 3 is "+someNum.somFun(3));
System.out.println("Factorial of 6 is "+someNum.somFun(6));
}
// Overridden methods not require if using Lamda expression
@Override
public double getValue() {
// 'remove implements'
// No overriding require
// no object creation required for calling method
return 123.44;
}
//Not required if using Lamda Expression
@Override
public boolean test(int i) {
boolean flag = i%2 == 0;
return flag;
}
@Override
public boolean test(int x, int y) {
//logic which returns boolean
if(x>y){
System.out.println("x is greater than y");
}
return false;
}
}
package lamda.first;
public class EmptyArrayException extends Exception {
EmptyArrayException(){
super("Empty Array");
}
}
package lamda.first;
import lamda.userdefined.functional.interfaces.DoubleNumericArrayFunc;
import lamda.userdefined.functional.interfaces.StringFunc;
public class LamdaAsArgsDemo {
public static void main(String[] args) throws EmptyArrayException{
String inputStr = "Lamda adds power";
String outStr;
System.out.println("Input string is : " + inputStr);
// parssing single line/singe method
outStr = StringOper(String::toLowerCase, inputStr);
System.out.println("Output String is : "+outStr);
//passing block as function
outStr = StringOper(str->{
String s="";
for (int i=str.length()-1;i>=0;i--){
s=s+str.charAt(i);
}
return s;
},inputStr);
System.out.println("Output String is :"+ outStr);
//passing instance as functional parameter
StringFunc strfuc = str -> {
String s = "";
for (int i = str.length() - 1; i >= 0; i--) {
s = s + str.charAt(i);
}
return s;
};
outStr = StringOper(strfuc,"Hello World...");
System.out.println("out put by Passing reference : "+outStr);
//Lamda EXCEPTION DEMO
double d[] = {1.0, 2.0, 3.0, 4.0, 5.0};
DoubleNumericArrayFunc average = n-> {
if(n.length ==0){
throw new EmptyArrayException();
}
double sum = 0.0;
for (int i=0; i<n.length; i++){
sum = sum+n[i];
}
return sum;
};
System.out.println("Average of given values is : "+average.func(d));
System.out.println("Average of given input is "+ average.func(new double[0]));
}
public static String StringOper(StringFunc sf, String s) {
return sf.func(s);
}
}
package lamda.function;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
public class Example1 {
public static void main(String[] args) {
//example1
Function<String, Integer> obj = s -> s.length();
System.out.println("length is " + obj.apply("ambition"));
//example2
Function<Integer, String> function = i -> i * 1125 + " rupees on given sqft";
System.out.println(function.apply(50));
// andThen and compose examples
Function<String, String> obj1 = x -> "first" + x;
Function<String, String> obj2 = x -> "second" + x;
//andThen
Function<String, String> andThen1 = obj1.andThen(obj2);
System.out.println("andThen Output1 : " + andThen1.apply("CheckObject"));
Function<String, String> andThen2 = obj2.andThen(obj1);
System.out.println("andThen Output2 : " + andThen2.apply("CheckObject"));
//compose
Function<String, String> compose1 = obj1.compose(obj2);
System.out.println("compose Output1 : " + compose1.apply("CheckObject"));
Function<String, String> compose2 = obj2.compose(obj1);
System.out.println("compose Output2 : " + compose2.apply("CheckObject"));
//The identity function in math is one in which the
// output of the function is equal to its input.
//BiFunction
BiFunction<Integer, Integer, Integer> f1 = Integer::sum;
System.out.println(f1.apply(34, 12)); //returns and print 46
//a basic andThen() example with BiFunction
Function<Integer, Integer> f2 = a -> a * a;
System.out.println(f1.andThen(f2).apply(11, 13));
}
}
package lamda.function;
import lamda.pojo.Employee;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Example2 {
public static void main(String[] args) {
//Employee List
List<Employee> empList = new ArrayList<>();
empList.add(new Employee(123, "ashoke", "manager", 10001.00));
empList.add(new Employee(424, "bharat", "lead", 10002.00));
empList.add(new Employee(621, "chandu", "director", 10005.00));
empList.add(new Employee(93, "danish", "developer", 10006.00));
empList.add(new Employee(448, "eenadu", "developer", 10001.00));
//Without Streams
Function<Employee, String> function = emp-> emp.getName();
ArrayList<String> empNames = new ArrayList<>();
for (Employee emp : empList) {
empNames.add(function.apply(emp));
}
empNames.forEach(System.out::println);
//Get Data WITH Streams
List<String> empNames1 = empList.stream().map(function).collect(Collectors.toList());
//List<String> empNames1 = empList.stream().map(Employee::getName).collect(Collectors.toList());
//List<String> empNames1 = empList.stream().map(e->e.getName()).collect(Collectors.toList());
empNames1.forEach(e-> System.out.println(e+" : streams"));
}
}
package lamda.operator;
import com.sun.deploy.net.MessageHeader;
import java.util.*;
import java.util.function.BinaryOperator;
public class BinaryExample {
public static void main(String[] args) {
// ->
BinaryOperator<Integer> operator1 = BinaryOperator.maxBy((x, y) -> x.compareTo(y));
System.out.println("result is : " + operator1.apply(33, 44));// 44
// ::
BinaryOperator<Integer> operator2 = BinaryOperator.minBy(Integer::compareTo);
System.out.println("result is : " + operator2.apply(33, 44)); //33
BinaryOperator<Integer> sort = BinaryOperator.maxBy((x,y)->x>y ? 1 : ((x==y)?0:-1));
System.out.println("result is : " + sort.apply(33, 44));
}
}
package lamda.optional;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
//It is used to represent a value is present or not
//a way to deal with null values
public class OptionalExamples {
public static void main(String[] args) {
Optional<String> empty = Optional.empty();
Optional<String> nonEmpty = Optional.of("FIFA Worldcup 2022");
//check empty
Optional.ofNullable("hyderabad").ifPresent(System.out::println); //hyderabad
System.out.println(empty.isPresent()); //false
System.out.println(nonEmpty.isPresent()); //true
//Check Null
Optional<Object> nullCheck = Optional.ofNullable(null);
Optional<String> nullCheck1 = Optional.of(null);
System.out.println("is ofNullable "+nullCheck);//
System.out.println("is Null "+nullCheck1.get());// NPE
//filter(Predicate)
Predicate<String> year = s->s.contains("2022");
System.out.println(nonEmpty.filter(year));//Optional[FIFA Worldcup 2022]
System.out.println(empty.filter(year));// Optional.empty
System.out.println(nonEmpty.filter(x->x.startsWith("FIFA")).get());
//map(Function)
Function<String, String> func = x-> x.substring(5,13);
System.out.println(nonEmpty.map(func).get()); //Worldcup
System.out.println(nonEmpty.map(x->x.toLowerCase()).get()); //fifa worldcup 2022
//flatmap(Function)
Optional<Optional<String>> opopS = Optional.of(Optional.of("FIFA Worldcup 2022"));
Function<String, String> func1 = x->x.concat(" Qatar");
System.out.println(opopS.map(x->x.map(func1)).get());//Optional[FIFA Worldcup 2022 Qatar]
System.out.println(opopS.flatMap(x->x.map(func1)).get());//FIFA Worldcup 2022 Qatar
//orElse
System.out.println(nonEmpty.orElse("Next Cup")); //FIFA Worldcup 2022
System.out.println(empty.orElse("Next Cup")); // Next Cup
//exception
System.out.println(nonEmpty.orElseThrow(NullPointerException::new)); //FIFA Worldcup 2022
System.out.println(empty.orElseThrow(NullPointerException::new));//Exception in thread "main" java.lang.NullPointerException
}
}
package lamda.pojo;
import java.util.Objects;
public class Address {
private int hno;
private String street;
private String city;
private String state;
public Address(int hno, String street, String city, String state) {
this.hno = hno;
this.street = street;
this.city = city;
this.state = state;
}
public int getHno() {
return hno;
}
public void setHno(int hno) {
this.hno = hno;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public String toString() {
return "Address{" +
"hno=" + hno +
", street='" + street + '\'' +
", city='" + city + '\'' +
", state='" + state + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Address address = (Address) o;
return hno == address.hno && Objects.equals(street, address.street) && Objects.equals(city, address.city) && Objects.equals(state, address.state);
}
@Override
public int hashCode() {
return Objects.hash(hno, street, city, state);
}
}
package lamda.pojo;
public class Employee {
private int empId;
private String name;
private String designation;
private double salary;
private Address address;
public Employee(int empId, String name, String designation, double salary) {
this.empId = empId;
this.name = name;
this.designation = designation;
this.salary = salary;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"empId=" + empId +
", name='" + name + '\'' +
", designation='" + designation + '\'' +
", salary=" + salary +
'}';
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
package lamda.predicate;
import lamda.pojo.Employee;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
//
public class Example1 {
public static void main(String[] args) {
Predicate<String> getLength = str-> str.length()< 12;
boolean result = getLength.or(str -> str.length() >5).and(s->s.contains("A")).test("Application");
System.out.println("Matches given condition ? :"+result);
Predicate<String> strLength1 = x->x.length()>8;
//Override test method
Predicate<String> strLength2 = new Predicate<String>() {
@Override
public boolean test(String s) {
return s.length()<12;
}
};
System.out.println(strLength2.negate().test("balboa is the seveth part"));
System.out.println(strLength1.test("balboa is the seveth part"));
}
}
package lamda.predicate;
import lamda.pojo.Employee;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Example2 {
public static void main(String[] args) {
//and conditions
Predicate<Employee> isLead = e -> e.getDesignation().contains("lead");
Predicate<Employee> highSalary = e->e.getSalary()>10000.00;
Predicate<Employee> data = isLead.and(highSalary).and(e -> e.getAddress() != null).negate();
//or
boolean test = data.or(e -> e.getName().startsWith("b")).test(new Employee(424, "bharat", "lead", 10002.00));
System.out.println("Is employee lead : "+test);
//Employee List
List<Employee> empList = new ArrayList<Employee>();
empList.add(new Employee(123,"ashoke","manager",10001.00));
empList.add(new Employee(424,"bharat","lead",10002.00));
empList.add(new Employee(621,"chandu","director",10005.00));
empList.add(new Employee(93,"danish","developer",10006.00));
empList.add(new Employee(448,"eenadu","developer",10001.00));
List<Employee> employeeList = empList.stream().filter(isLead).collect(Collectors.toList());
//BiPredicate
BiPredicate<Integer, Double> id = (x,y)-> x>400 && y<10006.00;
List<Employee> employees = empList.stream().filter(input -> id.test(input.getEmpId(), input.getSalary())).collect(Collectors.toList());
employees.forEach(System.out::println);
}
}
package lamda.supplier;
import java.util.*;
import java.util.function.Supplier;
public class Example1 {
public static void main(String[] args) throws Exception {
Supplier<String> supp = ()->"Hello Java";
Supplier<Exception> suppExp = ()-> new RuntimeException("some message...");
System.out.println( supp.get());
List<String> list1 = Arrays.asList("abc12", "def", "ghi");
List<String> list2 = Collections.emptyList();
String result1 = list1.stream().findAny().orElseGet(supp);
String result2 = list2.stream().findFirst().orElseThrow(suppExp);
System.out.println(result1);
System.out.println(result2);
//get Object
List<Object> emptyList = getListObject().get();
}
public static <E> Supplier<List<E>> getListObject(){
//return ArrayList::new;
return ()->new ArrayList<E>();
}
}
package lamda.userdefined.functional.interfaces;
import lamda.first.EmptyArrayException;
public interface DoubleNumericArrayFunc {
double func(double[] d) throws EmptyArrayException;
}
package lamda.userdefined.functional.interfaces;
public interface MyNumber {
double getValue();
}
package lamda.userdefined.functional.interfaces;
public interface NumericFunc {
int func(int n);
}
package lamda.userdefined.functional.interfaces;
public interface NumericTest {
boolean test(int i);
}
package lamda.userdefined.functional.interfaces;
public interface NumericTest2 {
boolean test(int x, int y);
}
package lamda.userdefined.functional.interfaces;
public interface SomeFunc<T> {
T somFun(T t);
}
package lamda.userdefined.functional.interfaces;
public interface StringFunc {
String func(String str);
}
package nisum.rte.examples;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toMap;
public class Demo {
public static void main(String[] args) {
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(3,"apple");
hashMap.put(4,"orange");
hashMap.put(2,"banana");
hashMap.put(9,"mango");
hashMap.put(5,"leeche");
TreeMap<Integer, String> map = new TreeMap<>();
map.putAll(hashMap);
for (Map.Entry<Integer,String> newEntry: map.entrySet()) {
System.out.println("Unsorted Keys : "+ newEntry.getKey());
}
//java 8 sorting which returns Set
Set<Integer> collect = hashMap.keySet().stream().sorted(Integer::compareTo).collect(Collectors.toCollection(LinkedHashSet::new));
//System.out.println(collect);
//Sorting returns map (Sort by Key)
Stream<Map.Entry<Integer, String>> sortedStream = hashMap.entrySet().stream().sorted(Map.Entry.comparingByKey());
//sortedStream.forEach(System.out::println);
//Descending order
LinkedHashMap<Integer, String> lhmDescendingOrder = hashMap.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y) -> y, LinkedHashMap::new));
Set<Map.Entry<Integer, String>> entries = hashMap.entrySet(); // get entries then
Stream<Map.Entry<Integer, String>> stream = entries.stream(); // get Stream
Stream<Map.Entry<Integer, String>> sorted1 = stream.sorted(Map.Entry.comparingByKey());// expects one comparator
//sorted1.forEach(System.out::println);
//Sorting by Values and Collecting in new Map object
LinkedHashMap<Object, Object> linkedHashMap = new LinkedHashMap<>();
Stream<Map.Entry<Integer, String>> sorted2 = hashMap.entrySet().stream().sorted(Map.Entry.comparingByValue());
// sorted2.forEach(x->linkedHashMap.put(x.getKey(),x.getValue()));
// System.out.println("--------------------------------");
// System.out.println(linkedHashMap);
/**
* Sort Keys in Ascending order
*/
hashMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(System.out::println);
/**
* Sort Keys in Descending order
*/
hashMap.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).forEach(System.out::println);
}
}
package stream.basic;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CollectorsDemo {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 20, 30, 11, 20, 33, 4, 44, 55, 20);
System.out.println("original :"+numbers);
//Collectors.toSet
Set<Integer> integerSet = numbers.stream().collect(Collectors.toSet());
System.out.println("AfterSet :"+integerSet);
//Collectors.toList
List<Integer> intList = numbers.stream().collect(Collectors.toList());
System.out.println("AfterList :"+intList);
//Collectors.toCollection
//creates any collection object
ArrayList<Integer> array = numbers.stream().collect(Collectors.toCollection(ArrayList::new));
//Collection.toMap
//key will not add duplicates neither overrides, so using set as input
Map<Integer, String> mapCollect = integerSet.stream().collect(Collectors.toMap(Function.identity(), String::valueOf));
System.out.println(mapCollect);
//Collectors.joining
//Joins th input, return only String.
String joined = numbers.stream().map(String::valueOf).collect(Collectors.joining("-"));
System.out.println(joined);
//Collestors.groupingBy
Map<String, Set<Integer>> collect = numbers.stream().collect(Collectors.groupingBy(String::valueOf, Collectors.toSet()));
System.out.println(collect);
Optional<Integer> op= Optional.of(9455);
op.isPresent();
}
}
package stream.basic;
import stream.basic.pojo.Employee;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectorsDemo2 {
public static void main(String[] args) {
List<Employee> employeeList = new ArrayList<>();
employeeList.add(new Employee(100, "gautam", 47, "North America", 450000));
employeeList.add(new Employee(200, "adani", 25, "North America", 50000));
employeeList.add(new Employee(300, "mukesh", 30, "Asia", 450000));
employeeList.add(new Employee(400, "ambani", 59, "Africa", 450000));
List<String> names = employeeList.stream().map(e -> e.getName()).collect(Collectors.toList());
System.out.println(names); //[gautam, adani, mukesh, ambani]
//summingInt : summing all salaries
Double collect = employeeList.stream().collect(Collectors.summingDouble(e -> e.getSal()));
//Integer collect = employeeList.stream().mapToInt(Employee::getId).sum();
System.out.println(collect); //1400000.0
//averaging: taking average of all salaries
Double average = employeeList.stream().collect(Collectors.averagingDouble(e -> e.getSal()));
System.out.println(average); //350000.0
//counting
Long count = employeeList.stream().filter(e->e.getSal()>100000).collect(Collectors.counting());
System.out.println(count); //3
//joining
String join = employeeList.stream().map(Employee::getName).collect(Collectors.joining("-","**","**"));
//******************************************************************************************************************
Optional<List<Employee>> opListEmp = Optional.of(employeeList);
//System.out.println("---------------"+opListEmp);
System.out.println(join);
//Optional[[stream.basic.pojo.Employee@3d494fbf, stream.basic.pojo.Employee@1ddc4ec2, stream.basic.pojo.Employee@133314b, stream.basic.pojo.Employee@b1bc7ed]]
//groupingBy
Stream<Employee> stream = employeeList.stream();
Map<String, List<Employee>> collect1 = stream.collect(Collectors.groupingBy(e -> e.getName(), Collectors.toList()));
System.out.println(collect1);
//reducing of Collectors class
Comparator<Employee> empComparator = (e1, e2) -> e1.getId() - e2.getId();
Optional<Employee> reducingOptinal = employeeList.stream().collect(Collectors.reducing(BinaryOperator.minBy(empComparator)));
if (reducingOptinal.isPresent()) {
System.out.println("Min Emp using reducing() method : " + reducingOptinal.get());
}
}
}
package stream.basic;
import stream.basic.pojo.Customer;
import stream.basic.pojo.LineItem;
import java.util.*;
import java.util.stream.Collectors;
public class CollectorsDemo3 {
public static void main(String[] args) {
//Object 1
LineItem lineItem1 = new LineItem(1001, "Item 1", new Date(2010, 07, 01));
LineItem lineItem2 = new LineItem(1002, "Item 2", new Date(2020, 07, 01));
LineItem lineItem3 = new LineItem(1003, "Item 3", new Date(2030, 07, 01));
LineItem lineItem4 = new LineItem(1004, "Item 4", new Date(2040, 07, 01));
LineItem lineItem5 = new LineItem(1005, "Item 5", new Date(2050, 07, 01));
List<LineItem> lineItemsList1 = new ArrayList<>();
lineItemsList1.add(lineItem1);
lineItemsList1.add(lineItem2);
lineItemsList1.add(lineItem3);
lineItemsList1.add(lineItem4);
lineItemsList1.add(lineItem5);
Customer customer1 = new Customer(100, "Customer 1", true, "M", lineItemsList1);
//Object 2
LineItem lineItem6 = new LineItem(2001, "Item 6", new Date(2010, 07, 01));
LineItem lineItem7 = new LineItem(2002, "Item 7", new Date(2020, 07, 01));
List<LineItem> lineItemsList2 = new ArrayList<>();
lineItemsList2.add(lineItem6);
lineItemsList2.add(lineItem7);
Customer customer2 = new Customer(200, "Customer 2", true, "F", lineItemsList2);
//Object 3
LineItem lineItem8 = new LineItem(2003, "Item 8", new Date(2040, 07, 01));
LineItem lineItem9 = new LineItem(3004, "Item 9", new Date(2070, 07, 01));
LineItem lineItem10 = new LineItem(3005, "Item 10", new Date(2200, 07, 01));
List<LineItem> lineItemsList3 = new ArrayList<>();
lineItemsList3.add(lineItem8);
lineItemsList3.add(lineItem9);
lineItemsList3.add(lineItem10);
Customer customer3 = new Customer(300, "Customer 3", true, "M", lineItemsList3);
Customer customer4 = new Customer(400, "Customer 4", true, "F", new ArrayList<LineItem>());
//Adding all 4 countomers to List.
List<Customer> customersList = new ArrayList<>();
customersList.add(customer1);
customersList.add(customer2);
customersList.add(customer3);
customersList.add(customer4);
//Flatmap
}
}
package stream.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StreamDemo {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10,13,5,15,12,20);
//filter
list.stream().filter(x->x%2==0).forEach(System.out::println);
//parallel stream
List<Integer> list1 = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list1.add(i);
}
list1.parallelStream().forEach(System.out::println);
}
}
package stream.basic;
public class StreamDemo2 {
}
package stream.basic.pojo;
import java.util.List;
public class Customer {
private int id;
private String name;
private boolean active;
private String gender;
private List<LineItem> lineItems;
public Customer(int id, String name, boolean active, String gender, List<LineItem> lineItems) {
super();
this.id = id;
this.name = name;
this.active = active;
this.gender = gender;
this.lineItems = lineItems;
}
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 boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public List<LineItem> getLineItems() {
return lineItems;
}
public void setLineItems(List<LineItem> lineItems) {
this.lineItems = lineItems;
}
}
\ No newline at end of file
package stream.basic.pojo;
public class Employee {
private int id;
private String name;
private int age;
private String region;
private double sal;
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 getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public double getSal() { return sal; }
public void setSal(double sal) { this.sal = sal; }
public Employee(int id, String name, int age, String region, double sal) {
this.id = id;
this.name = name;
this.age = age;
this.region = region;
this.sal = sal;
}
}
\ No newline at end of file
package stream.basic.pojo;
import java.util.Date;
public class LineItem {
private int itemId;
private String itemName;
private Date manfacturedDate;
public LineItem(int itemId, String itemName, Date manfacturedDate) {
super();
this.itemId = itemId;
this.itemName = itemName;
this.manfacturedDate = manfacturedDate;
}
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Date getManfacturedDate() {
return manfacturedDate;
}
public void setManfacturedDate(Date manfacturedDate) {
this.manfacturedDate = manfacturedDate;
}
@Override
public String toString() {
return "LineItem [itemId=" + itemId + ", itemName=" + itemName + ", manfacturedDate=" + manfacturedDate + "]";
}
}
package stream.rte;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
List<Employee> employeeList = new ArrayList<Employee>();
employeeList.add(new Employee(111, "Jiya Brein", 32, "Female", "HR", 2011, 25000.0));
employeeList.add(new Employee(122, "Paul Niksui", 25, "Male", "Sales And Marketing", 2015, 13500.0));
employeeList.add(new Employee(133, "Martin Theron", 29, "Male", "Infrastructure", 2012, 18000.0));
employeeList.add(new Employee(144, "Murali Gowda", 28, "Male", "Product Development", 2014, 32500.0));
employeeList.add(new Employee(155, "Nima Roy", 27, "Female", "HR", 2013, 22700.0));
employeeList.add(new Employee(166, "Iqbal Hussain", 43, "Male", "Security And Transport", 2016, 10500.0));
employeeList.add(new Employee(177, "Manu Sharma", 35, "Male", "Account And Finance", 2010, 27000.0));
employeeList.add(new Employee(188, "Wang Liu", 31, "Male", "Product Development", 2015, 34500.0));
employeeList.add(new Employee(199, "Amelia Zoe", 24, "Female", "Sales And Marketing", 2016, 11500.0));
employeeList.add(new Employee(200, "Jaden Dough", 38, "Male", "Security And Transport", 2015, 11000.5));
employeeList.add(new Employee(211, "Jasna Kaur", 27, "Female", "Infrastructure", 2014, 15700.0));
employeeList.add(new Employee(222, "Nitin Joshi", 25, "Male", "Product Development", 2016, 28200.0));
employeeList.add(new Employee(233, "Jyothi Reddy", 27, "Female", "Account And Finance", 2013, 21300.0));
employeeList.add(new Employee(244, "Nicolus Den", 24, "Male", "Sales And Marketing", 2017, 10700.5));
employeeList.add(new Employee(255, "Ali Baig", 23, "Male", "Infrastructure", 2018, 12700.0));
employeeList.add(new Employee(266, "Sanvi Pandey", 26, "Female", "Product Development", 2015, 28900.0));
employeeList.add(new Employee(277, "Anuj Chettiar", 31, "Male", "Product Development", 2012, 35700.0));
/**
* getGender
*/
Map<String, Long> getNoOfMaleAndFemales = employeeList.stream().
collect(Collectors.groupingBy(Employee::getGender, Collectors.counting()));
//System.out.println(getNoOfMaleAndFemales); //{Male=11, Female=6}
/**
* find all Departments
*/
Stream<String> department = employeeList.stream().map(Employee::getDepartment).distinct();
//department.forEach(System.out::println);
/**
* get Highest Salary
*/
Optional<Employee> highestPaidEmployee= employeeList.stream().max(Comparator.comparingDouble(Employee::getSalary));
//System.out.println(highestPaidEmployee.get().getSalary());
/**
* grouping By Examples
*/
Map<String, List<Employee>> collect1 = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment));
Map<Integer, List<Employee>> collect2 = employeeList.stream().collect(Collectors.groupingBy(z -> z.getAge()));
Map<Integer, Long> collect = employeeList.stream().collect(Collectors.groupingBy(Employee::getAge, Collectors.counting()));
//System.out.println(collect);
/**
* Get Employee names who joined after 2012
*/
List<String> empNames = employeeList.stream().filter(f -> f.getYearOfJoining() > 2015).map(Employee::getName).collect(Collectors.toList());
//empNames.forEach(System.out::println);
/**
* Count the number of employees in each department
*/
Map<String, Long> noOfEmpByDepart = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));
//noOfEmpByDepart.forEach((key, value) -> System.out.println(key + " : " + value));
/**
* Get the max salary of employee in each department
*/
Map<String, Employee> maxSalaryByDepartment = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Employee::getSalary)), Optional::get)));
//maxSalaryByDepartment.forEach((s, employee) -> System.out.println(s+"--"+employee.getSalary()));
}
}
package stream.rte;
public class Employee {
private int id;
private String name;
private int age;
private String gender;
private String department;
private int yearOfJoining;
private double salary;
public Employee(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 String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
public String getDepartment() {
return department;
}
public int getYearOfJoining() {
return yearOfJoining;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Id : " + id
+ ", Name : " + name
+ ", age : " + age
+ ", Gender : " + gender
+ ", Department : " + department
+ ", Year Of Joining : " + yearOfJoining
+ ", Salary : " + salary;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment