Posts

Showing posts from August, 2019

Java 8 Collection removeIf method with code samples

Java 8 has added a new method called removeIf to the Collection interface. You can use this to remove an element from a Collection in Java. In this article, I will be explaining the how this method works. Edit What does RemoveIf do? This method removes an element from the Collection that matches a particular condition. It returns a boolean value which indicates whether some values were removed or not.  The condition to be checked is specified via a Predicate instance. Predicate is an in-built functional interfac e that accepts an argument of any data type and returns a boolean.  You can implement it via a lambda expression . RemoveIf Integer Code Sample The following code demonstrates this method on an Integer List: public class RemoveIfDemo { public static void main(String[] args) { List<Integer> input = new ArrayList<Integer>(); input.add(5); input.add(12); input.add(17); input.add(18); input.add(25); boolean anyElementRemoved = input.remo

Java 8 Iterator forEachRemaining method with code samples

Java 8 has added a method called forEachRemaning to the Iterator interface. This helps in using an Iterator to internally iterate over a Collection, without an explicit loop. In this article, I will be covering this method with a code sample. Edit Pre Java 8 code Before Java 8, you had to write code similar to the following in order to use an Iterator: public class ForEachRemainingDemo { public static void main(String[] args) { List<Integer> input = Arrays.asList(5, 3, 11, 15, 9, 2, 5, 11); Iterator<Integer> itr = input.iterator(); while(itr.hasNext()) System.out.println(itr.next()); }} So in this code, you need to use a while loop in order to use the iterator to iterate through the input list. Using Java 8 forEachRemaining Java 8 added the forEachRemanining method to the Iterator interface. So using this method, the above code can be re-written as follows: public class ForEachRemainingDemo { public static void main(String[] args) { List<Intege

Spring REST client using RestTemplate in Eclipse and Maven

Image
In this article, I will be demonstrating how you can create a Spring REST client using RestTemplate. In order to see how you can create a simple Spring REST service, you can refer to this blog post. What is Spring RESTTemplate? Spring provides a class called RestTemplate . This is the starting point in creating a REST client application.  It uses the URI and the HTTP method to invoke in order to connect to a REST service. It has several methods that allow you to invoke the HTTP methods on the specified URI Edit Project Creation Step 1 – Create a Maven Project in Eclipse . You can refer to this blog post. You will get a project as follows:   Step 2 – Add dependencies to POM file. Add the following to your pom.xml file: <properties> <spring.framework>5.1.3.RELEASE</spring.framework> <spring.web>5.1.3.RELEASE</spring.web> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId&g

Spring @ExceptionHandler annotation explained

In this article, I will be explaining the Spring @ExceptionHandler annotation and how it can be used for exception handling in Spring . Introduction You can specify the @ExceptionHandler annotation on a method in a controller class and mark the method as an exception handling method. Along with the annotation you need to specify the exceptions that the method handles. So when an exception of the specified type occurs, Spring uses the exception handler method to handle the exception.  Within the exception handler method, you can specify any exception handling code like returning an error code or redirecting to an error page, etc. Edit The following code sample demonstrates this: @RestControllerpublic class PersonController { @GetMapping(value = "/person/{personId}", produces = { "text/plain" }) public Person getPersonWithId(@PathVariable Integer personId) { // Returns hardcoded data, a real world application would return from // the database re

Java 9 Stream takeWhile with examples

Java 8 introduced the Stream API which allows processing and applying some operations to the elements in a Collection.  Java 9 has made some improvements to the Stream API . One such improvement is the takeWhile method. In this article, I will be covering the Java 9 Stream takeWhile method in detail. I will also be writing some Java 9 takeWhile examples. The takeWhile method operates on a Stream. It accepts a Predicate instance and applies the Predicate to all the elements in the input stream and produces an output stream. It behaves differently depending on whether the input Stream is ordered or unordered. takeWhile on Ordered Stream As per the API documentation, when the takeWhile is applied on an ordered Stream, it returns, a stream consisting of the longest prefix of elements taken from this stream that match the given predicate if the stream is ordered. So basically, the takeWhile method applies the Predicate on each element in the input Stream until the condition in the Predica

Java Protected Keyword explained With Code Samples

In this article, I will be covering the Java Protected Keyword. Introduction Just like private and public, protected is an access specifier. When the protected access specifier is used for a field or method, it becomes accessible in all the subclasses of the class in which the field is defined. The protected access specifier also makes the member accessible in other classes which are in the same package as the class having the protected member.   Accessing a protected field from a sub-class The following code snippet demonstrates how you can access a protected field in a sub-class: package demo;public class Base {private int a;protected int b;}public class Sub extends Base {public void subMethod() {super.a=4; //this causes compilation errorsuper.b=9;}} The class Base has a private field a and a protected field b The class Sub extends Base It has a method subMethod which assigns some values to a and b a=4; – This causes a compilation error since a is private b=9 – This does not c

Java 8 DoubleSupplier Example

In this blog post, I will be explaining how the DoubleSupplier Java 8 functional interface works. To know more about functional interfaces, you can refer this blog post. Edit The  DoubleSupplier interface provides a method called getAsDouble This method does not accept any arguments. It returns a Double data type. The DoubleSupplier interface is a specialization of the Supplier interface that returns a double value. To see an example of the Supplier interface, refer to this blog post. DoubleSupplier example Consider the following code snippet: public class DoubleSupplierDemo { public static void main(String[] args) { DoubleSupplier getRandom = () -> new Random().nextDouble(); System.out.println("Random number 1 = "+getRandom.getAsDouble()); System.out.println("Random number 2 = "+getRandom.getAsDouble()); }}   Here, we have implemented the DoubleSupplier.getAsDouble method using a lambda expression.  This getAsDouble method simple returns a ra

Java 8 LocalTime class in with code samples

What is LocalTime class? The Java 8 LocalTime class represents a time. It has the hour, minute, second and nanoseconds components. So for example, you can use it to represent a time like 7:30. It does not have a date, year or month component. Edit LocalTime Creation There are several static methods on this class that can be used to create a LocalTime object. The following code demonstrates this: LocalTime time1 = LocalTime.now();System.out.println("Current time is "+time1);LocalTime time2 = LocalTime.parse("12:30");System.out.println("time2 is "+time2);LocalTime time3 = LocalTime.of(5, 30);System.out.println("time3 is "+time3);   The LocalTime.now returns the current time. The LocalTime.parse parses the specified time and creates a LocalTime object out of it. It requires the Time to be in hh-mm format. If you specify the time in some other format, an error will occur. If your String time is in any other format, you can use the overloaded ve

Stream API AllMatch in Java 8 with examples

In this blog post, I will be demonstrating the allMatch method provided by Java 8 Stream API. Edit In order to understand the Stream API in detail, refer to  this  blog post. Code Sample with Integer You can use the  allMatch method to determine if all the elements in a Collection matches a particular condition. Consider the following code snippet: public class AllMatchIntegerDemo { public static void main(String[] args) { List<Integer> input = Arrays.asList(5, 3, 11, 15, 9, 2, 5, 11); boolean found = input.stream().allMatch(num -> num % 2 == 0); System.out.println("All even numbers: "+found); }} This code checks if all the numbers in the input stream are even. First, the code obtains a  Stream  on the input ArrayList using the  stream() method. Then the code invokes the  allMatch method on the stream instance. This method accepts a  Predicate  instance.  Predicate  is an in-built functional interface.  Refer  this  blog post for a detailed  Predic