Archive
Java 8 : Predicate example
Java 8 introduces functional style of programming.
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
Here we have list with integers, if we want to print even numbers from it, will write something like below
public List<Integer> printEvenNumbers(List<Integer> list){ List<Integer> result = new ArrayList<Integer>(); for(Integer i : list){ if(i%2 == 0){ result.add(i); } } return result; }
Now if we want to print odd numbers, so will write something like below
public List<Integer> printOddNumbers(List<Integer> list){ List<Integer> result = new ArrayList<Integer>(); for(Integer i : list){ if(i%2 != 0){ result.add(i); } } return result; }
Except the if condition, everything is copy pasted. Again if we want the numbers only divisible by 3, again we have to copy paste entire code just by changing the if condition.
If we have a chance to pass the if condition as a argument to method, then we would have achieved both requirements with only one method, for this java 8 introduced an interface called java.util.function.Predicate<T>
Complete example:
import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class PredicateTest{ public static void main(String [] a) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7); System.out.println("Print all numbers:"); condition(list, (n)->true); System.out.println("Print no numbers:"); condition(list, (n)->false); System.out.println("Print even numbers:"); condition(list, (n)-> n%2 == 0 ); System.out.println("Print odd numbers:"); condition(list, (n)-> n%2 == 1 ); System.out.println("Print numbers greater than 5:"); condition(list, (n)-> n > 5 ); } public static void condition(List<Integer> list, Predicate<Integer> predicate) { for(Integer n: list) { if(predicate.test(n)) { System.out.println(n + " "); } } } }
Java 8 : Double Colon operator
Double Colon operator introduced in Java 8, We use it as method reference.
Syntax : ClassName::MethodName
for example, if we want to print a list :
List<String> strings = Arrays.asList("one","two"); strings.forEach(System.out::println);
here forEach is a new method added to the List interface in java 8. System.out is the PrintStream Class and println is method in it.
Complete Example:
import java.util.*; import java.util.stream.*; public class DoubleColon{ public static void display(String name){ System.out.println("Name : "+name); } public static void main(String[] args){ List<String> names = Arrays.asList("one","two","three"); names.forEach(DoubleColon::display); } }
Java 8 : Functional Interface Example
To Support lambda expressions in Java 8, they introduced Functional Interfaces.
An interface which has Single Abstract Method can be called as Functional Interface.
Runnable, Comparator,Cloneable are some of the examples for Functional Interface. We can implement these Functional Interfaces by using Lambda expression.
For example:
Thread t =new Thread(new Runnable(){ public void run(){ System.out.println("Runnable implemented by using Lambda Expression"); } });
This is the old way of creating a Thread.
As Runnable is having Single Abstract Method, we can consider this as a Functional Interface and we can use Lambda expression like below.
Thread t = new Thread(()->{ System.out.println("Runnable implemented by using Lambda Expression"); });
Here instead of passing Runnable object we just passed lambda expression.
Declaring our own Functional Interfaces:
We can declare our own Functional Interface by defining Single Abstract Method in interface.
public interface FunctionalInterfaceTest{ void display(); } //Test class to implement above interface public class FunctionInterfaceTestImpl { public static void main(String[] args){ //Old way using anonymous inner class FunctionalInterfaceTest fit = new FunctionalInterfaceTest(){ public void display(){ System.out.println("Display from old way"); }}; fit.display();//outputs: Display from old way //Using lambda expression FunctionalInterfaceTest newWay = () -> {System.out.println("Display from new Lambda Expression");} newWay.display();//outputs : Display from new Lambda Expression } }
We can annotate with @FunctionalInterface annotation, to tell compile time errors. It is optional
for ex:
@FunctionalInterface public interface FunctionalInterfaceTest{ void display(); void anotherDisplay();//shows an error, FunctionalInterface should have only one abstarct method. }
Default Method:
Functional interface can not have more than one abstract method but it can have more than one default methods.
Default methods are introduced in Java 8, to add new methods to interface with out disturbing the implemented classes.
interface DefaultInterfaceTest{ void show(); default void display(){ System.out.println("Default method from interface can have body..!"); } } public class DefaultInterfaceTestImpl implements DefaultInterfaceTest{ public void show(){ System.out.println("show method"); } //we dont need to provide any implementation to default method. public static void main(String[] args){ DefaultInterfaceTest obj = new DefaultInterfaceTestImpl(); obj.show();//out puts: show method obj.display();//outputs : Default method from interface can have body..! } }
Main use of default method is with out forcing the implemented class , we can add a method to an interface.
Multiple Inheritance:
If the same default method is there in two interfaces and one class is implementing that interface, then it will throw an error.
//Normal interface with show method interface Test{ default void show(){ System.out.println("show from Test"); } } //Another interface with same show method interface AnotherTest{ default void show(){ System.out.println("show from Test"); } } //Main class to implement above two interfaces class Main implements Test, AnotherTest{ //here is an ambiguity which show method has to inherit here }
This class wont compile because there is an ambiguity between Test, AnotherTest interfaces show() method, to resolve this we need to override show() method to Main Class.
class Main implements Test, AnotherTest{ void show(){ System.out.println("Main show method"); } }
Java 8 : Lambda Example
Lambda Expressions:
Lambda expressions are new and important feature of Java 8. They provide a clear way to represent one method interface using lambda expression. And they provide easy way to access Collection libraries for iterating, filter and extract data.
Example :
Syntax : (arg1, arg2) -> {body}
For Ex:
(int a, int b) -> { return a + b; } () -> System.out.println("Hello World"); (String s) -> { System.out.println(s); } //Old way of iterating Collection List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7); for(Integer n: list) { System.out.println(n); } //New way with lambda: List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7); list.forEach(n -> System.out.println(n));
Rules:
- It can have zero or more number of arguments.
- Parameters are separated by using comma
- Empty parenthesis are used to represent empty parameters eg : () -> System.out.println(“Hello World”);
- Curly braces for body is not mandatory if it contains only single statement, other wise it should enclosed with curly braces.
Program:
interface TestInterface{ void display(); } public class TestInterfaceImpl{ public static void main(String[] args){ TestInterface li = new TestInterface(){ public void display(){ System.out.println("Hello World"); } }; li.display(); } }
Here we used anonymous class to implement TestInterface and this interface has only one method, by using lambda expression without using anonymous class we can call the display() method
interface TestInterface{ void display(); } public class TestInterfaceImpl{ public static void main(String[] args){ //Old way: TestInterface old = new TestInterface(){ public void display(){ System.out.println("Old : Display method called!"); } }; old.display(); //New way with Lambda expression TestInterface li = () -> System.out.println("New : Display method called !"); li.display(); } }
This approach we regularly use in Java Swing, while adding an action to Swing Component we use ActionListener actionPerformed() method, ActionListener is an interface which has only one method called actionPerformed(),
//old way: button.addActionListener(new ActionListener()){ public void actionPerformed(ActionEvent e){ System.out.println("The button was clicked using old fashion code!"); } } //New way: button.addActionListener( (e) -> { System.out.println("The button was clicked. From lambda expressions !"); });
java.util.Runnable also has only one method public void run(), this also we can represent using lambda
//old way Runnable r = new Runnable(){ public void run(){ System.out.println("Runnable run method"); } } //New way with lambda expression Runnable r = ()->System.out.println("Runnable run method"); //So we can create Thread object like below Thread t = new Thread(()->{System.out.println("Runnable run method from lambda")});
Any interface which has only one method can be used with lambda expression instead of old anonymous inner class.
Thanks for reading.
Java RPC style Webservice with JAX-WS
We have to create two projects one is WebService server project and WebService client project, here client will call the methods of Server.
1. Creating Server project:
Create an interface with @WebService annotation, and annotate the method with @WebMethod whitch you wanted to expose as web service.
package com.java2practice.ws; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.Style; @WebService @SOAPBinding(style = Style.RPC) public interface WebServiceInterface{ @WebMethod int sum(int firstNumber, int secondNumber); }
2. Create an implementation to the above interface like below
package com.java2practice.ws; import javax.jws.WebService; @WebService(endpointInterface = "com.java2practice.ws.WebServiceInterface") public class WebServiceImpl implements WebServiceInterface{ @Override public int sum(int firstNumber, int secondNumber) { return firstNumber + secondNumber; } }
3. Now we have to publish this webservice by using EndPoint.
package com.java2practice.ws; import javax.xml.ws.Endpoint; import com.java2practice.ws.WebServiceImpl; public class WebServicePublisher{ public static void main(String[] args) { Endpoint.publish("http://localhost:7777/webservice/testws", new WebServiceImpl()); } }
- When we run the above code, webservice will be published and can be accessed by using http://localhost:7777/webservice/testws URL.
- To see the generated WSDL file click http://localhost:7777/webservice/testws?wsdl. And the generated WSDL look like
<pre>-<!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2.4-b01. --> <!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2.4-b01. --> <definitions targetNamespace="http://ws.java2practice.com/" name="WebServiceImplService"><types/> <message name="sum"><part name="arg0" type="xsd:int"/><part name="arg1" type="xsd:int"/></message> <message name="sumResponse"><part name="return" type="xsd:int"/></message> <portType name="WebServiceInterface"><operation name="sum" parameterOrder="arg0 arg1"> <input wsam:Action="http://ws.java2practice.com/WebServiceInterface/sumRequest" message="tns:sum"/> <output wsam:Action="http://ws.java2practice.com/WebServiceInterface/sumResponse" message="tns:sumResponse"/> </operation></portType><binding name="WebServiceImplPortBinding" type="tns:WebServiceInterface"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/> <operation name="sum"><soap:operation soapAction=""/> <input> <soap:body use="literal" namespace="http://ws.java2practice.com/"/> </input> <output> <soap:body use="literal" namespace="http://ws.java2practice.com/"/> </output> </operation> </binding> <service name="WebServiceImplService"> <port name="WebServiceImplPort" binding="tns:WebServiceImplPortBinding"> <soap:address location="http://localhost:7777/webservice/testws"/> </port> </service> </definitions>
Our webservice server project is fine, now we have to create client program, for this we have to use wsimport command, this will be available in java.
- Go to command prompt and give wsimport it will show all the options which are there in wsimport, if it doesn’t show any thing set the path variable to jdk/bin.
- wsimport -keep http://localhost:7777/webservice/testws?wsdl -d D:\java2practice\Desktop\client
- It will generate the files, and copy those files to your IDE and create a client program like below.
package com.java2practice.ws; public class WebServiceClient { public static void main(String[] args) { WebServiceImplService service = new WebServiceImplService(); WebServiceInterface serviceInterface = service.getWebServiceImplPort(); int sum = serviceInterface.sum(10, 20); System.out.println("answer : "+sum);//outputs answer as 30 } }
Thanks for reading.
How to send multiple rows of data to Spring Controller
Common requirement would be sending multiple rows of data to Spring Controller.
We use @RequestParam String value to hold the single form field. But when we dealing with multiple rows @RequestParam String value won’t work.
If It is single row like below like below
S.NO | First Name | Last Name | Age |
1 | AAA | BBB | 23 |
We can use @RequestParam annotation to capture the form data:
public String saveEmployee(@RequestParam Integer sNo, @RequestParam String firstName, @RequestParam String firstName, @RequestParam Integer age){ //here we can access the form data. }
Suppose we have a form with multiple rows. Then We have to use @RequestParam String[] values,
Let’s see the example below:
S.NO | First Name | Last Name | Age |
1 | AAA | BBB | 23 |
2 | CCC | DDD | 24 |
3 | EEE | FFF | 28 |
And here is the Controller Code:
public String saveEmployees(@RequestParam Integer[] sNo, @RequestParam[] String firstName, @RequestParam[] String lastName, @RequestParam[] Integer age){ //first row data Integer sNo_0 = sNo[0]; String firstName_0 = firstName[0]; String lastName_0 = lastName[0]; Integer age_0 = age[0]; //second row data Integer sNo_1 = sNo[1]; String firstName_1 = firstName[1]; String lastName_1 = lastName[1]; Integer age_1 = age[1]; //third row data Integer sNo_2 = sNo[2]; String firstName_2 = firstName[2]; String lastName_2 = lastName[2]; Integer age_2 = age[2]; }
Thanks for reading.