<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/">

<channel>
	<title>Programming Archives - Manish Sanger</title>
	<atom:link href="https://www.manishsanger.com/tag/programming/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.manishsanger.com/tag/programming/</link>
	<description>Java, J2EE, Spring Framework, application security,big data,database,design patterns,hibernate,j2ee,java,jdbc,micro-services,mongodb,multithreading,nosql</description>
	<lastBuildDate>Wed, 28 Mar 2018 11:45:40 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>Java Exception Hierarchy</title>
		<link>https://www.manishsanger.com/java-exception-hierarchy/</link>
					<comments>https://www.manishsanger.com/java-exception-hierarchy/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Wed, 28 Mar 2018 11:45:40 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[exception]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=353</guid>

					<description><![CDATA[<p>As shown in the exception hierarchy, a Throwable class is a superclass of all errors and exceptions in Java. Objects those are instances of Throwable or one of its subclasses are thrown by JVM or by Java throw statement. Error: An Error is a subclass of Throwable that represents serious errors that can&#8217;t be handled. [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/java-exception-hierarchy/">Java Exception Hierarchy</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div id="attachment_354" style="width: 657px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-354" class="size-full wp-image-354" src="https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy.png" alt="Java Exception Hierarchy" width="647" height="593" srcset="https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy.png 647w, https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy-300x275.png 300w" sizes="(max-width: 647px) 100vw, 647px" /></a><p id="caption-attachment-354" class="wp-caption-text">Java Exception Hierarchy</p></div>
<p>As shown in the exception hierarchy, a <em>Throwable</em> class is a superclass of all errors and exceptions in Java. Objects those are instances of <em>Throwable</em> or one of its subclasses are thrown by JVM or by Java throw statement.</p>
<p><span style="text-decoration: underline;"><strong>Error:</strong></span><br />
An Error is a subclass of <em>Throwable</em> that represents serious errors that can&#8217;t be handled. A method is not required to declare throws clause for Error or any of its subclasses for the errors thrown during execution of the method but not caught.</p>
<p>Error and its subclasses are unchecked exceptions.<br />
Here are the examples of errors: OutOfMemoryError, StackOverflowError, AssertionError, IOError, NoClassDefFoundError etc.</p>
<p><span style="text-decoration: underline;"><strong>Exception:</strong></span><br />
Exception is a subclass of <em>Throwable</em>. Exception and its subclasses represent the problems from which a program can recover and should be handled by the application.<br />
Exception has two sub type:</p>
<p>1. <span style="text-decoration: underline;"><strong>RunTimeException or Unchecked Exception:</strong></span><br />
The classes that extends <em>RunTimeException</em> are called unchecked Exception. An unchecked exception occurs at run-time, it can&#8217;t be checked at compile time, an application should handle these exceptions. For example: NullPointerException, ArithmeticException, IllegalArgumentException, IndexOutOfBoundException etc.</p>
<p><span style="text-decoration: underline;"><strong>2. Checked Exception:</strong></span><br />
The classes that extends Throwable class except RunTimeExpception and Error are called Checked Exception. Checked exception are checked at compile time and application should handle these exceptions. For example: IOException, SQLException, FileNotFoundException, ClassNotFoundException, NoSuchMethodException etc.</p>
<p><span style="text-decoration: underline;"><strong>User-defined custom exception:</strong></span><br />
We can also create our own exception. Here are few rules:<br />
1. All exception must be a child of Throwable.<br />
2. To create a RuntimeException, we need to extend the RunTimeException class.<br />
3. To create the checked exception, we need to extend the Exception class.</p>
<p><span style="text-decoration: underline;"><strong>Reference:</strong></span><br />
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html" target="_blank">https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html</a><br />
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Error.html" target="_blank">https://docs.oracle.com/javase/8/docs/api/java/lang/Error.html</a></p>
<p>The post <a href="https://www.manishsanger.com/java-exception-hierarchy/">Java Exception Hierarchy</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/java-exception-hierarchy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy.png" length="35275" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/03/Exception-Hierarchy.png" width="647" height="593" medium="image" type="image/png"/>	</item>
		<item>
		<title>Type Erasure &#8211; Java Generics</title>
		<link>https://www.manishsanger.com/type-erasure-java-generics/</link>
					<comments>https://www.manishsanger.com/type-erasure-java-generics/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Tue, 20 Mar 2018 11:59:31 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[generics]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=344</guid>

					<description><![CDATA[<p>What is type Erasure? Generics in Java provide type checking at compile time and it has nothing to do at runtime. Java compiler uses Type Erasure feature to remove all generics type checking code (replace it with bound or Object if the type parameters are unbounded) in bytecode, insert type casting if necessary and generate [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/type-erasure-java-generics/">Type Erasure &#8211; Java Generics</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><b>What is type Erasure?</b></p>
<p>Generics in Java provide type checking at compile time and it has nothing to do at runtime. Java compiler uses <b>Type Erasure</b> feature to remove all generics type checking code (replace it with bound or Object if the type parameters are unbounded) in bytecode, insert type casting if necessary and generate bridge methods to preserve polymorphism in extended generic types.</p>
<p>Here is an example of generic a class:</p>
<pre><code class="java">class TypeErasureExample {<br />
private T t;</p>
<p>public TypeErasureExample(T t) {<br />
this.t = t;<br />
}</p>
<p>public T getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<p><b>After compilation the type will be replaced with String as follows:</b></p>
<pre><code class="java">class TypeErasureExample {<br />
private String t;</p>
<p>public TypeErasureExample(String t) {<br />
this.t = t;<br />
}</p>
<p>public String getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<p><u><b>Type erasure at class or class variable level:</b></u><br />
At the class level, type parameters on the class are removed at compile time and replaced with its first bound or Object if the type parameter is unbound.<br />
Here are few examples:<br />
<b>Type erasure when type parameter is unbound:</b><br />
<pre><code class="java">class TypeErasureUnboundExample {<br />
private T t;</p>
<p>public TypeErasureUnboundExample(T t) {<br />
this.t = t;<br />
}</p>
<p>public T getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<p><b>After compilation the type will be replace with Object (because type parameter is unbound) as follows:</b><br />
<pre><code class="java">class TypeErasureUnboundExample {<br />
private Object t;</p>
<p>public TypeErasureUnboundExample(Obhect t) {<br />
this.t = t;<br />
}</p>
<p>public Object getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<p><b>Type erasure when type parameter is bound:</b><br />
<pre><code class="java">class TypeErasureExample {<br />
private T t;</p>
<p>public TypeErasureExample(T t) {<br />
this.t = t;<br />
}</p>
<p>public T getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<p><b>After compilation the type will be replaced with String (with first bound) as follows:</b></p>
<pre><code class="java">class TypeErasureExample {<br />
private String t;</p>
<p>public TypeErasureExample(String t) {<br />
this.t = t;<br />
}</p>
<p>public String getT() {<br />
return t;<br />
}<br />
}<br />
</code></pre>
<u><b>Type Erasure at method level:</b></u><br />
Method type parameters are converted to its parent type Object if its unbound or its bound class when its bound:</p>
<p>For example:<br />
If type parameter is unbounded:<br />
<pre><code class="java">public static <T> void genericMethod(T t){<br />
        System.out.println(t);<br />
    }<br />
</code></pre>
<p>Will be converted to following at compile time:<br />
<pre><code class="java">public static void genericMethod(Object t){<br />
        System.out.println(t);<br />
    }<br />
</code></pre>
<p>If type parameter is bounded:</p>
<pre><code class="java">public static <T extend String> void genericMethod(T t){<br />
        System.out.println(t);<br />
    }<br />
</code></pre>
<p>Will be converted to following at compile time:<br />
<pre><code class="java">public static void genericMethod(String t){<br />
        System.out.println(t);<br />
    }<br />
</code></pre>
<p>The post <a href="https://www.manishsanger.com/type-erasure-java-generics/">Type Erasure &#8211; Java Generics</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/type-erasure-java-generics/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/03/type-erasure-Java-generics.png" length="15679" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/03/type-erasure-Java-generics.png" width="703" height="160" medium="image" type="image/png"/>	</item>
		<item>
		<title>Java Generics</title>
		<link>https://www.manishsanger.com/java-generics/</link>
					<comments>https://www.manishsanger.com/java-generics/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Tue, 20 Mar 2018 08:34:44 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[bounded-type-parameter]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=334</guid>

					<description><![CDATA[<p>Generics are a feature of generic programming which was introduced in Java 5. This allows a type or method to work with various object types while providing compile-time type safety. For example, collection framework supports generics. We can use Hashset, ArrayList, HashMap etc. to store various type of objects, and while retrieving the data we [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/java-generics/">Java Generics</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Generics are a feature of generic programming which was introduced in Java 5. This allows a type or method to work with various object types while providing compile-time type safety. For example, collection framework supports generics. We can use Hashset, ArrayList, HashMap etc. to store various type of objects, and while retrieving the data we don&#8217;t need to type cast.<br />
In Java 5, java rewrote the collection framework to incorporate the generics.</p>
<p>Here is an example of ArrayList without using generics:</p>
<pre><code class="java">List names = new ArrayList();<br />
names.add("Manish");<br />
String name = (String) names.get(0); //Type casting when retrieving the element from the array list</p>
<p>Integer number = (Integer) names.get(0); //Run-time error, ClassCastException will be thrown.<br />
</code></pre>
<p>When we use the ArrayList without generics, will have to type cast when we retrieve the element from the ArrayList, as the program doesn&#8217;t know the type of element stored in ArrayList. Also, when we try to type cast the element in the wrong way as I did in the code above, trying to type cast the element to Integer it will throw run-time ClassCastException error. Without generics, we only get the errors at the run-time not at compile time.</p>
<p>We can rewrite the code using generics as follows:</p>
<pre><code class="java">List<String> names = new ArrayList();<br />
names.add("Manish");<br />
String name = names.get(0); //No type casting is required.<br />
</code></pre>
<p><b>Creating custom Java generic Class:</b><br />
We can create our own generic class. A generic type is a class or interface that is parameterized over types, we use angle bracket (<>) to specify the type parameter.<br />
Note: Type argument can&#8217;t be of a primitive type.</p>
<pre><code class="java">public class GenericExample<T> {<br />
    private T t;<br />
    public T getT() {<br />
        return t;<br />
    }<br />
    public void setT(T t) {<br />
        this.t = t;<br />
    }<br />
}</p>
<p>class GenericTest{<br />
    public static void main(String[] args) {<br />
        //Instance with String type<br />
        GenericExample<String> genericExample = new GenericExample<>();<br />
        genericExample.setT("Test");</p>
<p>        //Instance with Integer type<br />
        GenericExample<Integer> genericExample1 = new GenericExample<>();<br />
        genericExample1.setT(100);</p>
<p>        //Type argument can't be primitive type.<br />
    }<br />
}<br />
</code></pre>
<p><b>Class with multiple type parameters:</b></p>
<pre><code class="java">public class GenericExample<T, U> {<br />
    private T t;<br />
    private U u;</p>
<p>    public GenericExample(T t, U u) {<br />
        this.t = t;<br />
        this.u = u;<br />
    }<br />
}</p>
<p>class GenericTest{<br />
    public static void main(String[] args) {<br />
        //Instance with String type<br />
        GenericExample<String, Integer> genericExample = new GenericExample<>("Test", 100);<br />
    }<br />
}<br />
</code></pre>
<p><b>Generic Method</b><br />
We can also create the generic method or constructor, no need to parameterize the whole class.</p>
<pre><code class="java">class GenericMethodTest{<br />
    static <T> void genericMethod(T t){<br />
        System.out.println(t);<br />
    }<br />
    public static void main(String[] args) {<br />
        GenericMethodTest.<String>genericMethod("Test");<br />
        GenericMethodTest.genericMethod("Test 2"); //Using type interface<br />
    }<br />
}<br />
</code></pre>
<p>In the above code, we can specify the type when calling the method or can just call like a normal method without specifying any type, JVM will do it for you. This feature is called type interface.</p>
<p><b>Java generics bounded type parameters:</b><br />
If we want to restrict the type of objects which can be used as parametrized type:<br />
<pre><code class="java">class GenericBound<T extends List> {<br />
    private T t;</p>
<p>    public GenericBound(T t) {<br />
        this.t = t;<br />
    }<br />
}<br />
</code></pre>
<p><b>Java generic type naming convention (Best practices)</b><br />
As per the Java best practices, type parameter should be single and uppercase letters. Following are the commonly used type parameters:</p>
<ul>
<li>T &#8211; Type</li>
<li>E &#8211; Element (Used extensively in collection framework)</li>
<li>N &#8211; Number</li>
<li>K &#8211; Key</li>
<li>V &#8211; Value</li>
<li>S,U,V etc. &#8211; 2nd, 3rd, 4th types</li>
</ul>
<p>The post <a href="https://www.manishsanger.com/java-generics/">Java Generics</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/java-generics/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/03/Java-generics.png" length="15016" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/03/Java-generics.png" width="731" height="125" medium="image" type="image/png"/>	</item>
		<item>
		<title>Java Try with Resources</title>
		<link>https://www.manishsanger.com/try-with-resources/</link>
					<comments>https://www.manishsanger.com/try-with-resources/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Mon, 19 Feb 2018 11:50:16 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[try-with-resources]]></category>
		<category><![CDATA[file-handling]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Java 7]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=320</guid>

					<description><![CDATA[<p>A resource is an object that must be closed once the program is finished or done using it, for example, file resource, JDBC database connection resource, socket connection resource etc. Prior to Java 7, there was no auto resource management, we open the resource in a try block and close the resource in finally block. [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/try-with-resources/">Java Try with Resources</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>A resource is an object that must be closed once the program is finished or done using it, for example, file resource, JDBC database connection resource, socket connection resource etc.</p>
<p>Prior to Java 7, there was no auto resource management, we open the resource in a try block and close the resource in finally block. For example:</p>
<pre><code class="java">try{<br />
//open resources<br />
}catch(IOException){<br />
//Exception handling<br />
}finally{<br />
//close resource<br />
}<br />
</code></pre>
<p>In the above approach there were few drawbacks:</p>
<ol>
<li>It causes memory leaks and performance issue if the developer forgot to close the resource.</li>
<li>Finally block will always be executed, it doesn&#8217;t matter if the exception is thrown from the try block. It means, it tries to close the resource in finally block, even if it doesn&#8217;t exist which again cause an exception to be thrown from finally block.</li>
<li>Exception thrown from finally block will be propagated up the call stack, though exception from try block is more relevant.</li>
</ol>
<p><b><u>try-with-resource</u></b><br />
In Java 7, a new approach called &#8220;try-with-resources&#8221; is introduced for auto resource management. In this when try block finishes, it automatically closes the resource.</p>
<p>Here is an example for try-with-resource construct:<br />
<pre><code class="java">private static void readFile() throws IOException {<br />
try(FileInputStream input = new FileInputStream("file.txt")) {<br />
int data = input.read();<br />
while(data != -1){<br />
System.out.print((char) data);<br />
data = input.read();<br />
}<br />
}<br />
}<br />
</code></pre>
<p>&nbsp;</p>
<p><b>try-with-resource using multiple resources</b><br />
We can use multiple resources in try-with-resource block, it will automatically close both the resources when program finish executing try block.</p>
<pre><code class="java">private static void readFile() throws IOException {<br />
try(  FileInputStream input = new FileInputStream("file.txt");<br />
BufferedInputStream bufferedInput = new BufferedInputStream(input)<br />
) {<br />
int data = bufferedInput.read();<br />
while(data != -1){<br />
System.out.print((char) data);<br />
data = bufferedInput.read();<br />
}<br />
}<br />
}<br />
</code></pre>
<p>The resources are closed in reverse order of they are declared inside the try. <i>BufferedInputStream</i> will be closed first, then <i>FileInputStream</i>.<br />
&nbsp;<br />
<b><u>AutoCloseable Custom implementation</u></b><br />
Java 7 has introduced an interface <b><i>java.lang.AutoCloseable</i></b>. To use any resource in try-with-resource block, it must implement the AutoCloseable interface. We can also implement <i>java.lang.AutoCloseable</i> interface in our own classes and use them with the try-with-resources construct.<br />
<i>AutoCloseable </i>interface only has one method class <i>close()</i>. Here is the <i>AutoCloseable</i> interface:</p>
<pre><code class="java">public interface AutoCloseable {<br />
public void close() throws Exception;<br />
}<br />
</code></pre>
<p>&nbsp;<br />
<b><u>Exception handling with try-with-resource:</u></b><br />
If one or more exceptions are thrown by try block in try-with-resources, the exceptions thrown are <b><i>suppressed exception</i></b>.<br />
Java added an constructor and two methods in <b>Throwable</b> class to deal with suppressed exceptions. We can get these exceptions by using the <b><i>getSuppress()</i></b> method of <b>Throwable</b> class.</p>
<p><b><u>Advantages of using try-with-resource construct:</u></b></p>
<ol>
<li>Auto resource management.</li>
<li>More readable code.</li>
<li>No need of finally block just to close the resource.</li>
<li>Meaning &amp; relevant exceptions.</li>
</ol>
<p>The post <a href="https://www.manishsanger.com/try-with-resources/">Java Try with Resources</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/try-with-resources/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/02/Java-try-with-resource.png" length="34462" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/02/Java-try-with-resource.png" width="757" height="232" medium="image" type="image/png"/>	</item>
		<item>
		<title>Predicate &#8211; Functional Interface (Java 8)</title>
		<link>https://www.manishsanger.com/predicate/</link>
					<comments>https://www.manishsanger.com/predicate/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Thu, 04 Jan 2018 12:10:08 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[java 8]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[functional interface]]></category>
		<category><![CDATA[predicate]]></category>
		<guid isPermaLink="false">http://www.manishsanger.com/?p=287</guid>

					<description><![CDATA[<p>In mathematical logic, a predicate is commonly understood to be a Boolean-valued function P: X→ {true, false}, called the predicate on X. Informally, a predicate is a statement that may be true or false depending on the values of its variables. It can be thought of as an operator or function that returns a value [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/predicate/">Predicate &#8211; Functional Interface (Java 8)</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In mathematical logic, a <strong>predicate</strong> is commonly understood to be a Boolean-valued function P: X→ {true, false}, called the predicate on X.<br />
Informally, a predicate is a statement that may be true or false depending on the values of its variables. It can be thought of as an operator or function that returns a value that is either true or false. For example, predicates are sometimes used to indicate set membership: when talking about sets, it is sometimes inconvenient or impossible to describe a set by listing all of its elements. Thus, a predicate P(x) will be true or false, depending on whether x belongs to a set. [Ref: WikiPedia (<a href="https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)" target="_blank" rel="noopener">https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)</a>]
<p>In java 8, predicate is an functional interface <em>java.util.function.Predicate&lt;T&gt;</em> which defines an abstract method named test, that accepts an object of generic type T and returns a boolean. Predicate can be used as assignment target for a lambda expression or method reference.</p>
<p><strong>Example:</strong><br />
<pre><code class="java">package com.manishsanger.Predicate;</p>
<p>public class Vehicle {<br />
private String type;<br />
private Integer displacement;</p>
<p>public Vehicle(String type, Integer displacement) {<br />
this.type = type;<br />
this.displacement = displacement;<br />
}</p>
<p>@Override<br />
public String toString() {<br />
return "Vehicle - Type:" + this.getType() + ", Displacement:" + this.getDisplacement() +"cc";<br />
}</p>
<p>public String getType() {<br />
return type;<br />
}</p>
<p>public void setType(String type) {<br />
this.type = type;<br />
}</p>
<p>public Integer getDisplacement() {<br />
return displacement;<br />
}</p>
<p>public void setDisplacement(Integer displacement) {<br />
this.displacement = displacement;<br />
}<br />
}<br />
</code></pre>
<p>If we need to get the vehicle whose displacement is more that 1500 cc, we can write a predicate for it as below:</p>
<pre><code class="java">public class VehiclePredicate {<br />
public static Predicate&lt;Vehicle&gt; isDisplacementAbove1500() {<br />
return vehicle -&gt; vehicle.getDisplacement() &gt;= 1500;<br />
}<br />
}<br />
</code></pre>
<p>We can user this predicate in <em><strong>filter()</strong></em>, to filter list of vehicle by condition in the predicate.</p>
<pre><code class="java">package com.manishsanger.Predicate;</p>
<p>import java.util.Arrays;<br />
import java.util.List;<br />
import java.util.stream.Collectors;</p>
<p>public class Example {</p>
<p>public static void main(String[] args) {<br />
List&lt;Vehicle&gt; vehicles = Arrays.asList(<br />
new Vehicle("SUV", 2200),<br />
new Vehicle("SUV", 1800),<br />
new Vehicle("SEDAN", 1600),<br />
new Vehicle("HATCHBACK", 1400),<br />
new Vehicle("SUV", 2800)<br />
);</p>
<p>//Using default filter() method, using stream and lambda expression.</p>
<p>//return all Vehicles those have displacement more than 1500<br />
System.out.println("All vehicles those have displacement more than 1500, Using default filter() method.");<br />
vehicles.stream().filter(vehicle -&gt; {<br />
return vehicle.getDisplacement() &gt;= 1500;<br />
}).collect(Collectors.toList()).forEach(System.out::println);</p>
<p>//return all Vehicles those have displacement more than 1500<br />
System.out.println("All SUV those have displacement more than 1500, Using default filter() method.");<br />
vehicles.stream().filter(vehicle -&gt; {<br />
return vehicle.getType().equals("SUV") &amp;&amp; vehicle.getDisplacement() &gt;= 1500;<br />
}).collect(Collectors.toList()).forEach(System.out::println);</p>
<p>}<br />
}<br />
</code></pre>
<p>Following will be the output:<br />
<pre><code class="java">All vehicles those have displacement more than 1500, Using default filter() method.<br />
Vehicle - Type:SUV, Displacement:2200cc<br />
Vehicle - Type:SUV, Displacement:1800cc<br />
Vehicle - Type:SEDAN, Displacement:1600cc<br />
Vehicle - Type:SUV, Displacement:2800cc<br />
All SUV those have displacement more than 1500, Using default filter() method.<br />
Vehicle - Type:SUV, Displacement:2200cc<br />
Vehicle - Type:SUV, Displacement:1800cc<br />
Vehicle - Type:SUV, Displacement:2800cc<br />
</code></pre>
<pre><code class="java"></code></pre>
<p>We can also define our own custom filter method(), Now add a <em><strong>filterVehicles()</strong></em> method in <strong>VehiclePredicate</strong> class.<br />
<pre><code class="java">public static List&lt;Vehicle&gt; filterVehicles(List vehicles, Predicate&lt;Vehicle&gt; predicate) {<br />
return vehicles.stream().filter(predicate).collect(Collectors.toList());<br />
}<br />
</code></pre>
<p>Add following code to Main class, to filter data using custom Predicate filter:<br />
<pre><code class="java">//Using custom filter method and java 8 lambda<br />
System.out.println("\nAll vehicles those have displacement more than 1500, Using default custom filter method.");<br />
VehiclePredicate.filterVehicles(vehicles, vehicle -&gt; {<br />
return vehicle.getDisplacement() &gt;= 1500;<br />
}).forEach(System.out::println);<br />
</code></pre>
<p>Here is the output:<br />
<pre><code class="java">All vehicles those have displacement more than 1500, Using default custom filter method.<br />
Vehicle - Type:SUV, Displacement:2200cc<br />
Vehicle - Type:SUV, Displacement:1800cc<br />
Vehicle - Type:SEDAN, Displacement:1600cc<br />
Vehicle - Type:SUV, Displacement:2800cc<br />
</code></pre>
<p>Here is how you can filter the list without lambda expression:<br />
<pre><code class="java">//Using custom filter method and without lambda<br />
System.out.println("\nAll vehicles those have displacement more than 1500, Using default custom filter method without lambda.");<br />
VehiclePredicate.filterVehicles(vehicles, VehiclePredicate.isDisplacementAbove1500()).forEach(System.out::println);<br />
</code></pre>
<p>Here is the output, for the above block of code:<br />
<pre><code class="java">All vehicles those have displacement more than 1500, Using default custom filter method.<br />
Vehicle - Type:SUV, Displacement:2200cc<br />
Vehicle - Type:SUV, Displacement:1800cc<br />
Vehicle - Type:SEDAN, Displacement:1600cc<br />
Vehicle - Type:SUV, Displacement:2800cc<br />
</code></pre>
<p>Java 8 Predicate Methods<br />
Let’s now go through the methods available for Predicate:</p>
<p><strong>1. Default Predicate and (Predicate other)</strong></p>
<p>It returns a composed predicate that represents a logical AND of two predicates.</p>
<p>To understand this let&#8217;s add another predicate in the <strong>VehiclePredicates</strong> class:</p>
<pre><code class="java">public static Predicate&lt;Vehicle&gt; isTypeSUV() {<br />
return vehicle -&gt; vehicle.getType().equals("SUV");<br />
}<br />
</code></pre>
<p>Now we can apply <strong>and()</strong> and <strong>or()</strong> function if we want to predicate for Vehicle of type SUV and displacement more than 1500 cc.</p>
<p>Here is the code for Main method:<br />
<pre><code class="java">//Multiple filter with AND logical operator<br />
System.out.println("\nAll SUV those have displacement more than 1500, Using custom Predicate filter without lambda.");<br />
VehiclePredicate.filterVehicles(vehicles, VehiclePredicate.isDisplacementAbove1500().and(VehiclePredicate.isTypeSUV())).forEach(System.out::println);</p>
<p>//Multiple filter with OR logical operator<br />
System.out.println("\nAll Vehicle those have displacement more than 1500 or SUV, Using custom Predicate filter without lambda.");<br />
VehiclePredicate.filterVehicles(vehicles, VehiclePredicate.isDisplacementAbove1500().or(VehiclePredicate.isTypeSUV())).forEach(System.out::println);<br />
</code></pre>
<p>Here is the output:<br />
<pre><code class="java">All SUV those have displacement more than 1500, Using custom Predicate filter without lambda.<br />
Vehicle - Type:SUV, Displacement:2200cc<br />
Vehicle - Type:SUV, Displacement:1800cc<br />
Vehicle - Type:SUV, Displacement:2800cc</p>
<p>All Vehicle those have displacement more than 1500 or SUV, Using custom Predicate filter without lambda.<br />
Vehicle - Type:SUV, Displacement:2200cc<br />
Vehicle - Type:SUV, Displacement:1800cc<br />
Vehicle - Type:SEDAN, Displacement:1600cc<br />
Vehicle - Type:SUV, Displacement:2800cc<br />
</code></pre>
<p><strong>2. Default Predicate negate()</strong><br />
It return an predicate that represents logical NOT operator.</p>
<p>For example all Vehicles other than SUV:<br />
<pre><code class="java">//default negate(), Logical NOT operator. All vehicles other than SUV<br />
System.out.println("\nAll vehicles other than SUV, using negate()");<br />
VehiclePredicate.filterVehicles(vehicles, VehiclePredicate.isTypeSUV().negate()).forEach(System.out::println);<br />
</code></pre>
<p>Here is the output:<br />
<pre><code class="java">All vehicles other than SUV, using negate()<br />
Vehicle - Type:SEDAN, Displacement:1600cc<br />
Vehicle - Type:HATCHBACK, Displacement:1400cc<br />
</code></pre>
<p><strong>3. Boolean test (T t)</strong><br />
Predicate test evaluates this predicate on the given argument.<br />
For example we can pass an Vehicle object to check if this predicate return true or false:</p>
<p>Add the following code in main method:<br />
<pre><code class="java">//boolean test(T t) predicate<br />
System.out.println("\nboolean test predicate");<br />
Vehicle testVehicle = new Vehicle("SUV", 1000);<br />
System.out.println(VehiclePredicate.isTypeSUV().test(testVehicle));<br />
System.out.println(VehiclePredicate.isDisplacementAbove1500().test(testVehicle));<br />
</code></pre>
<p>Here is the output:<br />
<pre><code class="java">boolean test(T t) predicate<br />
true<br />
false<br />
</code></pre>
<p><strong>4. static Predicate isEqual(Object targetRef)</strong><br />
Returns a predicate that tests if two arguments are equal according to Objects.equals() method.</p>
<p>Let&#8217;s say we overridden <em><strong>equals()</strong></em> method for Vehicle class</p>
<pre><code class="java">@Override<br />
public boolean equals(Object obj) {<br />
Vehicle vehicle = (Vehicle) obj;<br />
if (this.getType().equals(vehicle.getType()) &amp;&amp; this.getDisplacement().equals(vehicle.getDisplacement())) {<br />
return true;<br />
}<br />
return false;<br />
}<br />
</code></pre>
<p>Now let&#8217;s say we have a Vehicle which has standard type &amp; displacement. Then we can get a Predicate, that will test if the given Vehicle is standard or not.</p>
<pre><code class="java">//static Predicate isEqual(Object targetRef)<br />
System.out.println("\nstatic Predicate isEqual(Object targetRef)");<br />
Predicate standardVehiclePredicate = Predicate.isEqual(new Vehicle("SUV", 1800));</p>
<p>System.out.println(standardVehiclePredicate.test(new Vehicle("SUV", 1800)));<br />
System.out.println(standardVehiclePredicate.test(new Vehicle("SUV", 1500)));<br />
</code></pre>
<p>Here is the output:<br />
<pre><code class="java">static Predicate isEqual(Object targetRef)<br />
true<br />
false<br />
</code></pre>
<p><a href="https://github.com/manishsanger/FunctionalInterface/tree/master/src/com/manishsanger/Predicate" target="_blank">Click here to see the source code</a></p>
<p>The post <a href="https://www.manishsanger.com/predicate/">Predicate &#8211; Functional Interface (Java 8)</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/predicate/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Functional Interface &#8211; Java 8</title>
		<link>https://www.manishsanger.com/functional-interface/</link>
					<comments>https://www.manishsanger.com/functional-interface/#comments</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Wed, 03 Jan 2018 10:41:05 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[java 8]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[functional interface]]></category>
		<category><![CDATA[predicate]]></category>
		<category><![CDATA[consumer]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=282</guid>

					<description><![CDATA[<p>Java has always been an Object Oriented programming language, it means we can&#8217;t have a function without its class. Other programming languages like C++, PHP, Python, JavaScript and many more, where we write functions and use anywhere, all these languages support functional programming along with Object Oriented programming. Java introduced Functional interface &#38; Lambda Expressions [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/functional-interface/">Functional Interface &#8211; Java 8</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Java has always been an <strong>Object Oriented</strong> programming language, it means we can&#8217;t have a function without its class. Other programming languages like C++, PHP, Python, JavaScript and many more, where we write functions and use anywhere, all these languages support functional programming along with Object Oriented programming.</p>
<p>Java introduced Functional interface &amp; Lambda Expressions in Java 8, to leverage functional programming to reduce verbosity.</p>
<p><strong>What is functional Interface?</strong></p>
<p>A <em>Functional Interface</em> is an interface which specifies exactly one abstract method. Its implementation may be treated as Lambda Expression.</p>
<p>Note: An interface is still a functional interface if it has many default methods, as long as it specifies only one abstract method.</p>
<p>Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface&#8217;s abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere</p>
<p>While the main use of Functional interfaces is for lambda expressions, method references, and constructor references, they can still be used, like any interface, with anonymous classes, implemented by classes, or created by factory methods.</p>
<p>Java 8 provides some inbuilt functional interfaces like <em>Comparable, Runnable, Callable</em> etc.</p>
<p>If you want to define any functional interface of your own, you can use annotation @FunctionalInterface for compiler level errors. It will allow to specify only one abstract method.</p>
<p>Example:</p>
<pre><code class="java">@FunctionalInterface<br />
public interface SomeInterface {<br />
public String someMethod(String param);<br />
}<br />
</code></pre>
<p>A functional interface is valid even if the @FunctionalInterface annotation would be omitted. It is only for informing the compiler to enforce single abstract method inside interface.</p>
<pre><code class="java">Public interface SomeInterface {<br />
String someMethod(String param);<br />
}</p>
<p>//With default method<br />
@FunctionalInterface<br />
Public interface SomeInterface {<br />
public String someMethod(String param);<br />
default void someDefaultMethod(){<br />
//method Implementation<br />
}</p>
<p>}</p>
<p>// When overriding methods from the java.lang.Object</p>
<p>@FunctionalInterface<br />
Public interface SomeInterface {<br />
public String someMethod(String param);<br />
@Override<br />
public String toString();  //Overridden from Object class</p>
<p>@Override<br />
public boolean equals(Object obj); //Overridden from Object class</p>
<p>}<br />
</code></pre>
<p>The signature of abstract method in functional interface is called <strong>Functional descriptor</strong> because it defines the signature of the lambda expression.</p>
<p>Java 8 has introduced several functional interfaces in java.util.function package which can be used to describe the signature of various lambda expressions.</p>
<p>Here is the complete list of functional interfaces available in java.util.functional:</p>
<p>1. <a href="https://www.manishsanger.com/predicate/">Predicate</a><br />
2. Consumer<br />
3. Function&lt;T, R&gt;<br />
4. Supplier<br />
5. UnaryOperator<br />
6. BinaryOperator<br />
7. BiPredicate&lt;L, R&gt;<br />
8. BiConsumer&lt;T, U&gt;<br />
9. BiFunction&lt;T, U, R&gt;</p>
<p>The post <a href="https://www.manishsanger.com/functional-interface/">Functional Interface &#8211; Java 8</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/functional-interface/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
