<?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>java 8 Archives - Manish Sanger</title>
	<atom:link href="https://www.manishsanger.com/tag/java-8/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.manishsanger.com/tag/java-8/</link>
	<description>Java, J2EE, Spring Framework, application security,big data,database,design patterns,hibernate,j2ee,java,jdbc,micro-services,mongodb,multithreading,nosql</description>
	<lastBuildDate>Tue, 08 May 2018 14:02:04 +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>PermGen to Metaspace in Java 8</title>
		<link>https://www.manishsanger.com/permgen-to-metaspace-in-java-8/</link>
					<comments>https://www.manishsanger.com/permgen-to-metaspace-in-java-8/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Tue, 08 May 2018 14:02:04 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[java 8]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=380</guid>

					<description><![CDATA[<p>In Java 8, PermGen space on the heap is replaced by Metaspace on native memory. The main difference between them is, Metaspace by default auto increases its size up to the memory provided by the Operating System, while PermGen always had a fixed maximum size. So, there will be fewer chances to get the OutOfMemoryError. [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/permgen-to-metaspace-in-java-8/">PermGen to Metaspace in Java 8</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In Java 8, <strong>PermGen</strong> space on the heap is replaced by <strong>Metaspace</strong> on native memory. The main difference between them is, <strong>Metaspace</strong> by default auto increases its size up to the memory provided by the Operating System, while <strong>PermGen</strong> always had a fixed maximum size. So, there will be fewer chances to get the <strong>OutOfMemoryError</strong>.<br />
When <strong>PermGen</strong> was initially introduced there was no dynamic class loading/unloading, so when the class was loaded it was there in <strong>PermGen</strong> until JVM shuts down. These days classes may be loaded/unloaded during the lifespan of JVM, so <strong>Metaspace</strong> makes more sense for the area where metadata is stored.</p>
<p><strong>Difference between PermGen and Metaspace:</strong></p>
<ul>
<li style="list-style-type: none;">
<ul>
<li><strong>PermGen</strong> had a fixed maximum size by default, where <strong>Metaspace</strong> size auto increases by default.</li>
<li><strong>PermGen</strong> max size can be changed using <b>-XX:MaxPermSize</b> option and <strong>Metaspace</strong> maximum size can also be fixed using <b>XX:MaxMetaspaceSize</b>.</li>
<li><strong>PermGen</strong> has comparatively inefficient garbage collection &#8211; frequent pauses and no concurrent deallocation. Where, <strong>Metaspace</strong> has comparatively efficient garbage collection &#8211; deallocated class data concurrently and not during GC pause.</li>
</ul>
</li>
</ul>
<p><strong>Metaspace garbage collection</strong></p>
<ol>
<li>Garbage collection of the dead classes and classloaders is triggered once the class metadata usage reaches the “<strong>MaxMetaspaceSize</strong>”.</li>
<li>Proper monitoring &amp; tuning of the Metaspace will obviously be required in order to limit the frequency or delay of such garbage collections. Excessive Metaspace garbage collections may be a symptom of classes, classloader memory leak or inadequate sizing for your application.</li>
</ol>
<p>There were few new flags added in Java 8 for Metaspace:</p>
<ol>
<li><b>-XX:MetaspaceSize=&lt;NNN&gt;</b><br />
Where &lt;NNN&gt; is the initial amount of space (initial high-water mark) allocated (in bytes)for class metadata that may induce a garbage collection to unload classes. After the amount of first high-water mark reached, the next high-water mark is managed by the garbage collector.</li>
<li><b>-XX:MaxMetaspaceSize=&lt;NNN&gt;</b><br />
Where &lt;NNN&gt; is the maximum amount of space allocated for class metadata (in bytes). This flag can be used to limit the amount of space allocated for class metadata, by default, there is no limit.</li>
<li><b>-XX:MinMetaspaceFreeRatio=&lt;NNN&gt;</b><br />
Where &lt;NNN&gt; is the minimum percentage of class metadata capacity free after a GC to avoid an increase in the amount of space (high-water-mark) allocated for class metadata that will induce a garbage collection.</li>
<li><b>-XX:MaxMetaspaceFreeRatio=&lt;NNN&gt;</b><br />
Where &lt;NNN&gt; is the maximum percentage of class metadata capacity free after a GC to avoid a reduction in the amount of space (high-water-mark) allocated for class metadata that will induce a garbage collection.</li>
</ol>
<p><b><i>Note:</i></b> Metaspace size auto increases in native memory as required to load class metadata if not restricted with <b>-XX:MaxMetaspaceSize<b>, It can bring down the whole server if not restricted. Be cautious to define this limit, so that we can avoid memory wastage.</p>
<p>The post <a href="https://www.manishsanger.com/permgen-to-metaspace-in-java-8/">PermGen to Metaspace in Java 8</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/permgen-to-metaspace-in-java-8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Introduction to Spring Boot</title>
		<link>https://www.manishsanger.com/introduction-to-spring-boot/</link>
					<comments>https://www.manishsanger.com/introduction-to-spring-boot/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Fri, 06 Apr 2018 13:22:13 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[java 8]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[microservices]]></category>
		<category><![CDATA[Spring]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=372</guid>

					<description><![CDATA[<p>What is Spring Boot? Spring is a popular Java-based framework for building web and enterprise grade application. spring framework provides various modern features via its various projects. Spring team created Spring Boot project to create standalone, production-ready spring based executable applications. Most of the spring boot application requires minimal spring configuration. Why Spring Boot? In [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/introduction-to-spring-boot/">Introduction to Spring Boot</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><strong>What is Spring Boot?</strong><br />
Spring is a popular Java-based framework for building web and enterprise grade application. spring framework provides various modern features via its various projects.<br />
Spring team created Spring Boot project to create standalone, production-ready spring based executable applications. Most of the spring boot application requires minimal spring configuration.</p>
<p><strong>Why Spring Boot?</strong><br />
In a traditional monolithic approach for developing web/RESTful application, a WAR is created and deployed on a web server like: Tomcat, Jboss, IBM WebSphere etc.<br />
From a microservices point of view, we need to develop services as executable, self-contained JAR files with an embedded HTTP listener.</p>
<p><strong>Spring Boot features:</strong></p>
<ol>
<li style="list-style-type: none;">
<ol>
<li><strong>Self-Contained web server:</strong> We can easily embed HTTP listeners for the web application. We can easily create a self-contained HTTP server using embedded tomcat, jetty etc.</li>
<li><strong>Standalone application:</strong> We can create a standalone executable application. It has SpringApplication class which provides the convenient way to bootstrap a spring application which can be started from the main method just by calling static method SpringApplication.run().</li>
<li><strong>Externalized configuration:</strong> It allows us to externalize the configuration so that we can work with the same application in various environments. We can use YAML files to externalize the configuration.</li>
<li><strong>YAML Support:</strong> It provides support for YAML configuration by default.</li>
<li><strong>Application Properties:</strong> It provides a rich set of application properties, for example: server-port, application-name and many more.</li>
<li><strong>Actuator:</strong> It provides production readiness by actuators such as metrics and health check.</li>
<li><strong>Type-safe configuration:</strong> It also provides a strong type-safe way to handle the configuration by allowing the developer to create a bean and populating it with the property value from a configuration file using annotation.</li>
<li><strong>Logging:</strong> It provides out of the box logging for all internal logging. Logback is provided by default without any additional configuration, which can be altered if needed.</li>
<li><strong>Security:</strong> It provides the feature of enabling the basic security by using the spring boot started security. It enables the basic security by default, which can be further enhanced to utilize the full strength of Spring security.</li>
</ol>
</li>
</ol>
<p><strong>Related Articles:</strong><br />
<a href="https://www.manishsanger.com/getting-started-with-spring-boot/"><strong>Getting started with Spring Boot, Create your first REST API application</strong></a></p>
<p>The post <a href="https://www.manishsanger.com/introduction-to-spring-boot/">Introduction to Spring Boot</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/introduction-to-spring-boot/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Getting started with Spring Boot, Create your first REST API application</title>
		<link>https://www.manishsanger.com/getting-started-with-spring-boot/</link>
					<comments>https://www.manishsanger.com/getting-started-with-spring-boot/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Fri, 06 Apr 2018 12:50:47 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[java 8]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[microservices]]></category>
		<category><![CDATA[Spring]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=364</guid>

					<description><![CDATA[<p>Spring Boot is been created for Rapid development. In this article will go through the steps to create first basic REST API using Spring Boot. We will see the more advanced version of this application in upcoming articles on microservices. Prerequisite: 1. Maven 3.X 2. Java 1.8/1.7 Getting Started &#8211; Step by Step guide The [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/getting-started-with-spring-boot/">Getting started with Spring Boot, Create your first REST API application</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Spring Boot is been created for Rapid development. In this article will go through the steps to create first basic REST API using Spring Boot. We will see the more advanced version of this application in upcoming articles on microservices.</p>
<p><span style="text-decoration: underline;"><strong>Prerequisite:</strong></span></p>
<p>1. Maven 3.X<br />
2. Java 1.8/1.7</p>
<p><span style="text-decoration: underline;"><strong>Getting Started &#8211; Step by Step guide</strong></span></p>
<p>The best way to bootstrap your Spring Boot projects is to use <a href="https://start.spring.io/" target="_blank" rel="noopener">Spring Initializr</a></p>
<p>It allows you to bootstrap various type of Spring Boot application from a simple web UI. You can select various available libraries from UI as per your requirement.</p>
<p>There are various option to generate, you can choose from Maven/Gradle project, with Java/Kotlin/Groovy and appropriate spring boot version. We will be using Maven, Java and Spring Boot 2.0.0 here.</p>
<p>Define group, artifact, name &amp; description of the application on the UI.</p>
<p>Click on &#8220;Switch to the full version&#8221; at the bottom left to see the list all available library options to be included in the project. For this article, I have selected the following as this is just a basic article to get started with Spring Boot.</p>
<p><strong>Web:</strong><br />
-Web<br />
-Jersey(JAX-RS)</p>
<p><strong>Ops:</strong><br />
-Actuator</p>
<p>Click on &#8220;Generate Project&#8221; button at the bottom of the screen to download bootstrap project with Spring Boot.</p>
<div id="attachment_365" style="width: 808px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-365" class="size-full wp-image-365" src="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr.png" alt="Spring Initializr- Spring Boot, bootstrap your first REST API application" width="798" height="581" srcset="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr.png 798w, https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr-300x218.png 300w, https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr-768x559.png 768w" sizes="(max-width: 798px) 100vw, 798px" /></a><p id="caption-attachment-365" class="wp-caption-text">Spring Initializr- Spring Boot, bootstrap your first REST API application</p></div>
<p>Import the project in your favorite IDE &#8211; Eclipse, IntelliJ Idea, STS or any other. I am using IntelliJ Idea on Mac OSX.</p>
<p>Project Structure will look like as follows:</p>
<div id="attachment_366" style="width: 310px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-boot-project-structure.png"><img decoding="async" aria-describedby="caption-attachment-366" class="size-full wp-image-366" src="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-boot-project-structure.png" alt="Spring boot - REST API project structure" width="300" height="359" srcset="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-boot-project-structure.png 300w, https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-boot-project-structure-251x300.png 251w" sizes="(max-width: 300px) 100vw, 300px" /></a><p id="caption-attachment-366" class="wp-caption-text">Spring boot &#8211; REST API project structure</p></div>
<p>Here is pom.xml dependencies, downloaded from Spring Initializr.</p>
<div id="attachment_367" style="width: 461px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/04/rest-api-dependencies.png"><img decoding="async" aria-describedby="caption-attachment-367" class="size-full wp-image-367" src="https://www.manishsanger.com/wp-content/uploads/2018/04/rest-api-dependencies.png" alt="Spring Boot REST API - maven dependencies" width="451" height="322" srcset="https://www.manishsanger.com/wp-content/uploads/2018/04/rest-api-dependencies.png 451w, https://www.manishsanger.com/wp-content/uploads/2018/04/rest-api-dependencies-300x214.png 300w" sizes="(max-width: 451px) 100vw, 451px" /></a><p id="caption-attachment-367" class="wp-caption-text">Spring Boot REST API &#8211; maven dependencies</p></div>
<p>spring-boot-starter-web &#8211; Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.</p>
<p>spring-boot-starter-actuator &#8211; Actuator provides production readiness of the application by monitoring our application, gathering metrics, understanding traffic, state of database etc. Will see actuator in more details in my next article.</p>
<p>Here is the Application file, which has the main method to run the Spring Boot application to make it executable:</p>
<pre><code class="java">@SpringBootApplication<br />
public class SpringbootdemoApplication {<br />
public static void main(String[] args) {<br />
SpringApplication.run(SpringbootdemoApplication.class, args);<br />
}<br />
}<br />
</code></pre>
<p>Create a Rest Controller, to create your first REST endpoint. Here is the code:</p>
<pre><code class="java">@RestController<br />
@RequestMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)<br />
public class HelloController {</p>
<p>@RequestMapping("/")<br />
public ResponseEntity&lt;Response&lt;List&gt;&gt; index() {<br />
HttpHeaders headers = new HttpHeaders();<br />
List listData = new ArrayList&lt;&gt;();<br />
listData.add("This is a First REST API with Spring boot");<br />
listData.add("Test2");</p>
<p>return new ResponseEntity&lt;&gt;(new Response&lt;&gt;(HttpStatus.OK.value(),<br />
"First Spring Boot REST API is working", listData), HttpStatus.OK);<br />
}<br />
}<br />
</code></pre>
<p>I create a class named Response to convert data to JSON and define a proper response format. This is not required, but I always prefer to have a class like this as it easy to format/standardize your response and pass HTTP status code &amp;message to variety of API consumers.</p>
<pre><code class="java">@JsonInclude(value = Include.NON_EMPTY)<br />
public class Response {</p>
<p>private int status;<br />
private String message;<br />
private T data;</p>
<p>public Response(int status, String message, T data) {<br />
super();<br />
this.status = status;<br />
this.message = message;<br />
this.data = data;<br />
}</p>
<p>public Response() {<br />
super();<br />
}</p>
<p>public int getStatus() {<br />
return status;<br />
}</p>
<p>public String getMessage() {<br />
return message;<br />
}</p>
<p>public T getData() {<br />
return data;<br />
}<br />
}<br />
</code></pre>
<p>You can also use lombok project (<a href="https://projectlombok.org/" target="_blank" rel="noopener">https://projectlombok.org/</a>), if you don&#8217;t want to write/generate getters &amp; setters.</p>
<p>That&#8217;s it, now we are ready to launch our first sample Spring Boot REST API project.</p>
<p>Go to Terminal and use the following commands to run the application.<br />
<pre><code class="bash">mvn clean install<br />
java -jar springbootdemo-0.0.1-SNAPSHOT.jar<br />
</code></pre>
<p>You can also run from your IDE. I am using IntelliJ Idea, so I can run it from IDE itself.</p>
<p>Once the run is complete, you can access it on http://localhost:8080/ or via postman. We haven’t made any configuration changes to it will run on localhost and default port 8080.</p>
<p>Here is the response:</p>
<div id="attachment_368" style="width: 451px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/04/API-Response.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-368" class="size-full wp-image-368" src="https://www.manishsanger.com/wp-content/uploads/2018/04/API-Response.png" alt="Spring Boot - REST API Response" width="441" height="141" srcset="https://www.manishsanger.com/wp-content/uploads/2018/04/API-Response.png 441w, https://www.manishsanger.com/wp-content/uploads/2018/04/API-Response-300x96.png 300w" sizes="auto, (max-width: 441px) 100vw, 441px" /></a><p id="caption-attachment-368" class="wp-caption-text">Spring Boot &#8211; REST API Response</p></div>
<p>You can access Actuator Health and Info as follows:<br />
http://localhost:8080/actuator/health<br />
http://localhost:8080/actuator/info</p>
<p>The post <a href="https://www.manishsanger.com/getting-started-with-spring-boot/">Getting started with Spring Boot, Create your first REST API application</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/getting-started-with-spring-boot/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr.png" length="76611" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/04/Spring-Initializr.png" width="798" height="581" 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[lambda]]></category>
		<category><![CDATA[functional interface]]></category>
		<category><![CDATA[predicate]]></category>
		<category><![CDATA[java 8]]></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>
		<item>
		<title>Lambda Expressions</title>
		<link>https://www.manishsanger.com/lambda-expressions/</link>
					<comments>https://www.manishsanger.com/lambda-expressions/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Tue, 02 Jan 2018 13:34:09 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java 8]]></category>
		<category><![CDATA[lambda]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=275</guid>

					<description><![CDATA[<p>Lambda expression is a concise representation of an anonymous function which can be passed as an argument to a method or stored in a variable. We call it anonymous function because it isn&#8217;t associated with a particular class like a method does and it doesn&#8217;t have a explicit name like a normal method. Like any [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/lambda-expressions/">Lambda Expressions</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Lambda expression is a concise representation of an anonymous function which can be passed as an argument to a method or stored in a variable.<br />
We call it anonymous function because it isn&#8217;t associated with a particular class like a method does and it doesn&#8217;t have a explicit name like a normal method. Like any regular method a lambda has a list of parameters, body, return type and list of exceptions which can be thrown.<br />
 <br />
Here are examples of lambda expressions:<br />
When value of lambda expression is stored in a variable:<br />
<pre><code class="java">Object var1 = (Object arg1, Object arg2) -> {System.out.println("Hello Lambda")};<br />
</code></pre>
 <br />
When lambda expression passed as an parameter to another method:<br />
<pre><code class="java">Object var1 = method(Object arg1, (Object arg2, Object arg3) -> {arg2 + arg3});<br />
</code></pre>
<p>Lambda expression explained:<br />
<div id="attachment_276" style="width: 551px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/01/Lambda-expression.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-276" src="https://www.manishsanger.com/wp-content/uploads/2018/01/Lambda-expression.png" alt="Lambda Expression" width="541" height="211" class="size-full wp-image-276" srcset="https://www.manishsanger.com/wp-content/uploads/2018/01/Lambda-expression.png 541w, https://www.manishsanger.com/wp-content/uploads/2018/01/Lambda-expression-300x117.png 300w" sizes="auto, (max-width: 541px) 100vw, 541px" /></a><p id="caption-attachment-276" class="wp-caption-text">Lambda Expression</p></div>
 <br />
Method signature (Parameters):<br />
Lambda function&#8217;s Method signature only have parameters, without any name or return as it&#8217;s an anonymous function.<br />
Lambda expression can have 0 or more parameters, same as any other regular method.<br />
 <br />
//Without parameters<br />
<pre><code class="java">() -> {System.out.println("Hello Lambda")};<br />
</code></pre>
<p>//With one parameters<br />
<pre><code class="java">(String hello) -> {System.out.println(hello)};<br />
</code></pre>
 <br />
//With two parameters<br />
<pre><code class="java">(String str1, String str2) -> {System.out.println(str1 + str2)};<br />
</code></pre>
 <br />
You can choose to not declare data type of the parameters, it will in inferred from the context.<br />
//Without defining the data type.<br />
<pre><code class="java">(a,b) -> {a+b}<br />
</code></pre>
<p>Note: Either you have to define the data type for all the parameters or none of them. You can&#8217;t choose define for some of them.<br />
 <br />
Lambda Operator (->)<br />
The arrow (->) separates the method signature from the implementation.<br />
 <br />
Method implementation (Lambda body ):<br />
Body of the Lambda expression can have expression or statements.<br />
Note:<br />
	1.	If there is only one statement in the body, curly braces are not required and return type is same as of body expression.<br />
	2.	If there are more than one statements, then is must be in curly braces and return type will be as value return form the code block, void if nothing is returned.<br />
 <br />
 <br />
Few more example of lambda expression:<br />
//no argument and returns void<br />
<pre><code class="java">() -> {}<br />
</code></pre> <br />
//no argument and returns a String Hello Lambda as an expression<br />
<pre><code class="java">() -> "Hello Lambda"<br />
</code></pre>
 <br />
//no argument and returns a String (using an explicit return statement)<br />
<pre><code class="java">() -> {return "Hello Lambda"}<br />
</code></pre> </p>
<p>The post <a href="https://www.manishsanger.com/lambda-expressions/">Lambda Expressions</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/lambda-expressions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/01/Lambda-expression.png" length="15930" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/01/Lambda-expression.png" width="541" height="211" medium="image" type="image/png"/>	</item>
		<item>
		<title>What new features were added in Java8?</title>
		<link>https://www.manishsanger.com/what-new-features-were-added-in-java8/</link>
					<comments>https://www.manishsanger.com/what-new-features-were-added-in-java8/#respond</comments>
		
		<dc:creator><![CDATA[manishsanger]]></dc:creator>
		<pubDate>Tue, 02 Jan 2018 13:31:00 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java 8]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[functional interface]]></category>
		<category><![CDATA[Stream API]]></category>
		<guid isPermaLink="false">https://www.manishsanger.com/?p=272</guid>

					<description><![CDATA[<p>Here are the list of high level features introduced in Java 8 along with lots of enhancement at complier and JVM level: 1. Lambda Expressions Lambda expression is a concise representation of an anonymous function which can be passed as an argument to a method or stored in a variable. Click Here more details 2. [&#8230;]</p>
<p>The post <a href="https://www.manishsanger.com/what-new-features-were-added-in-java8/">What new features were added in Java8?</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div id="attachment_273" style="width: 681px" class="wp-caption alignnone"><a href="https://www.manishsanger.com/wp-content/uploads/2018/01/Java-8.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-273" class="size-full wp-image-273" src="https://www.manishsanger.com/wp-content/uploads/2018/01/Java-8.png" alt="New features introduced in java 8" width="671" height="114" srcset="https://www.manishsanger.com/wp-content/uploads/2018/01/Java-8.png 671w, https://www.manishsanger.com/wp-content/uploads/2018/01/Java-8-300x51.png 300w" sizes="auto, (max-width: 671px) 100vw, 671px" /></a><p id="caption-attachment-273" class="wp-caption-text">New features introduced in java 8</p></div>
<p>Here are the list of high level features introduced in Java 8 along with lots of enhancement at complier and JVM level:</p>
<p>1. <a href="https://www.manishsanger.com/lambda-expressions/" target="_blank" rel="noopener" title="Lambda Expressions"><strong>Lambda Expressions</strong></a><br />
Lambda expression is a concise representation of an anonymous function which can be passed as an argument to a method or stored in a variable. <a href="https://www.manishsanger.com/lambda-expressions/" target="_blank" rel="noopener">Click Here more details</a></p>
<p>2. <a href="https://www.manishsanger.com/functional-interface/" target="_blank" rel="noopener" title="Functional Interface"><strong>Functional Interface</strong></a><br />
A Functional Interface is an interface which specifies exactly one abstract method. <a href="https://www.manishsanger.com/functional-interface/" target="_blank" rel="noopener" title="Functional Interface">Click Here more details</a><br />
3. <strong>Method References</strong><br />
4. <strong>Default methods in interface</strong><br />
5. <strong>Optional</strong><br />
6. <strong>Stream API</strong><br />
7. <strong>Date API</strong><br />
8. <strong>Nashorn, JavaScript Engine</strong></p>
<p>The post <a href="https://www.manishsanger.com/what-new-features-were-added-in-java8/">What new features were added in Java8?</a> appeared first on <a href="https://www.manishsanger.com">Manish Sanger</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.manishsanger.com/what-new-features-were-added-in-java8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<enclosure url="https://www.manishsanger.com/wp-content/uploads/2018/01/Java-8.png" length="17232" type="image/png"/><media:content url="https://www.manishsanger.com/wp-content/uploads/2018/01/Java-8.png" width="671" height="114" medium="image" type="image/png"/>	</item>
	</channel>
</rss>
