Posts

Showing posts with the label Java 8 Examples

IntBinaryOperator

In this blog post, I will be explaining how the Java 8 functional interface  IntBinaryOperator works. To know more about functional interfaces, you can refer to this  blog post. What is IntBinaryOperator IntBinaryOperator is an in-built functional interface in the java.util.Function package. It accepts two int arguments, operates on it and produces a result of type int . It is a specialization of the BinaryOperator interface. It has a applyAsInt method. It applies the logic in this method on the int arguments passed in and produces an int result. IntBinaryOperator Code Sample The following code demonstrates this   interface: IntBinaryOperator intBinaryOp = (num1,num2) -> num1+num2;int input1=14,input2=12;int result = intBinaryOp.applyAsInt(input1, input2);System.out.println("result:"+result); Line 1 declares a IntBinaryOperator instance intBinaryOp and implements it via a lambda expression that adds the input arguments and returns the result. Line 3 invokes the applyA...

putIfAbsent and getOrDefault Map methods with examples

In my earlier article, I had explained the Map.compute, Map.computeIfPresent and Map.computeIfAbsent methods added by Java 8. In addition, Java 8 has added two other methods called putIfAbsent and getOrDefault to the Map interface.  In this article, I will be explaining the these methods. Edit How putIfAbsent works Prior to Java 8, the Map interface had a put method. This method accepts a key and a value as a parameter and adds the key-value pair to the Map. If the key passed to this method is present in the Map, its value gets overwritten with the new value. However, sometimes, we may wish to add the key-value pair only if the key is absent from the Map. The putIfAbsent method caters to such situations. Thus, it accepts a key and a value as a parameter and adds the key-value pair to the Map only if the specified key is not present in the Map. If the key is present in the Map, it does not do anything. The following code demonstrates the put and putIfAbsent methods: Map<...

DoubleUnaryOperator in Java 8 With Code Sample

In this blog post, I will be explaining how the Java 8 functional interface  DoubleUnaryOperator works. To know more about functional interfaces, you can refer to this  blog post. Edit What is DoubleUnaryOperator DoubleUnaryOperator is an in-built functional interface in the java.util.Function package. It accepts an argument of double data type, operates on it and produces a result of type double . It is a specialization of the UnaryOperator interface. It has an applyAsDouble method. It applies the logic in this method on the double argument passed in and produces a double result. DoubleUnaryOperator Code Sample The following code demonstrates this   interface: DoubleUnaryOperator doubleUnaryOp = num -> Math.sqrt(num);double input = 9;double result = doubleUnaryOp.applyAsDouble(input);System.out.println("result:"+result); Line 1 declares a DoubleUnaryOperator instance doubleUnaryOp and implements it via a lambda expression that returns the square root of the in...

IntFunction in Java 8 With Code Sample

In this blog post, I will be explaining how the Java 8 functional interface  IntFunction  works. To know more about functional interfaces, you can refer to this  blog post. Edit What is IntFunction IntFunction is an in-built functional interface in the java.util.Function package. It accepts an argument of int data type, operates on it and produces a result of any data type. It is a specialization of the Function interface. It has an apply method. It applies the logic in this method on the int argument passed in and produces a result of the specified data type. IntFunction Code Sample The following code demonstrates this   interface: IntFunction<Double> doubleRetriever = input -> Double.valueOf(input);System.out.println("Double value " + doubleRetriever.apply(5)); This code implements this interface via a lambda expression that returns a result of Double type. It simply returns a Double value corresponding to the int input passed in. This code prints the f...

ToIntFunction in Java 8 With Code Sample

Functional interfaces and lambda expressions are one of the major features in Java 8. Java provides a lot of in-built functioal interfaces in the java.util.function package. One of these is the ToIntFunction. In this blog post, I will be explaining how thisfunctional interface works. To know more about functional interfaces, you can refer to this  blog post. Edit What is ToIntFunction ToIntFunction is an in-built functional interface in the java.util.Function package. It accepts an argument of any data type but returns a result of type int . It is a primitive specialization of the Function interface that always returns a result of int type. So IntFunction<T> is similar to Function<T,Integer> It has an applyAsInt  method. It then applies the logic in this method on the argument passed in to produce the int result. ToIntFunction Sample Code The following code snippet demonstrates this interface: ToIntFunction<String> strLengthProducer = str -> str.length()...

Java 8 DoubleToLongFunction Example

In this blog post, I will be explaining how the Java 8 functional interface  DoubleToLongFunction  works. To know more about functional interfaces, you can refer  this  blog post. Edit What is DoubleToLongFunction The DoubleToLongFunction  interface is a specialization of the  Function  interface. While the  Function interface accepts any data type, the DoubleToLongFunction  interface accepts as parameter a double value and returns a result of type long. To see an example of the Function  interface, refer to  this  blog post.   The DoubleToLongFunction  interface provides a method called  applyAsLong . It accepts a single parameter of double data type. It returns a result of long data type. So it basically applies the logic in the applyAsLong method to the input parameter and returns the result. DoubleToLongFunction Example Code The following code snippet demonstrates the DoubleToLongFunction  interface: DoubleToLongFunction longRetriever = input -> Double.valueOf(input)...

Java 8 DoubleToIntFunction Example

In this blog post, I will be explaining how the Java 8 functional interface DoubleToIntFunction works. To know more about functional interfaces, you can refer this blog post. Edit What is DoubleToIntFunction The DoubleToIntFunction  interface is a specialization of the  Function  interface. While the  Function interface accepts any data type, the DoubleToIntFunction  interface accepts as parameter a double value and returns a result of type int. To see an example of the Function  interface, refer to  this  blog post.   The DoubleToIntFunction interface provides a method called applyAsInt . It accepts a single parameter of double data type. It returns a result of int data type. So it basically applies the logic in the applyAsInt method to the input parameter and returns the result. DoubleToIntFunction Interface Example Code The following code snippet demonstrates the DoubleToIntFunction interface: DoubleToIntFunction integerRetriever = input -> Double.valueOf(input).i...

Java 8 DoubleBinaryOperator example

In this blog post, I will be explaining how the Java 8 DoubleBinaryOperator functional interface works. To know more about functional interfaces, you can refer  this  blog post. Edit What is DoubleBinaryOperator The DoubleBinaryOperator is a specialization of the BinaryOperator interface. To see an example of the   BinaryOperator interface, refer to  this  blog post. While the BinaryOperator interface accepts any data type, the DoubleBinaryOperator interface accepts arguments of double data type. The DoubleBinaryOperator  interface provides a method applyAsDouble . It accepts two arguments of double data type. It returns a result double data type. So it basically applies the logic in the applyAsDouble method to the input parameters and returns a double result. Code sample for DoubleBinaryOperator Consider the following code snippet: DoubleBinaryOperator multiplier = (a, b) -> a * b;double input1 = 6;double input2 = 5;System.out.println("Result of multiplying "...

How to add a number of days to a Date in Java

In this article, I will be demonstrating how to add a number of days to a Date in Java Edit Before Java 8 Prior to Java 8, the Date and Calendar classes were available for Date manipulation. They make operations like adding a number of days to a Date very difficult. The following code demonstrates adding days to a date using the Calendar class: String stringDate="2019-07-15"; Date date1=new SimpleDateFormat("yyyy-MM-dd").parse(stringDate); Calendar cal = Calendar.getInstance();cal.setTime(date1); // manipulate datecal.add(Calendar.DATE, 5); Date dateWith5Days = cal.getTime(); System.out.println(dateWith5Days); So the above code first uses SimpleDateFormat.parse to convert a String date to a java.util.Date. It then creates a Calendar object corresponding to this date. Finally, it uses the Calendar.add method to add days to the date. Using Java 8 Java 8 introduced the LocalDate class which makes date manipulations like adding/subtracting days/months very...

Java 8 LongSupplier explained with code samples

In this blog post, I will be explaining how the Java 8 functional interface LongSupplier works. To know more about functional interfaces, you can refer this blog post. Edit The LongSupplier interface provides a method called getAsLong. This method does not accept any arguments. It returns a Long data type. The LongSupplier interface is a specialization of the Supplier interface that returns an Long. To see an example of the Supplier interface, refer to this blog post. LongSupplier example Consider the following code snippet: LongSupplier getRandom = () -> new Random().nextLong();System.out.println("Random number 1 = "+getRandom.getAsLong());System.out.println("Random number 2 = "+getRandom.getAsLong());   Here, we have implemented the LongSupplier.getAsLong method using a lambda expression. This getAsLong method simple returns a random integer less than 100. So when this code is executed, it will print output similar to the following: Random number 1 ...

Java 8 Stream API Distinct method with code samples

In this article, I will be demonstrating the distinct method provided by Java 8 Stream API. In order to understand the Stream API in detail, refer to  this  blog post. Edit Introduction The Stream interface has a method called distinct. You can use this method to eliminate duplicates from a Stream. So you can use this to eliminate duplicates from a Collection. Using Stream.distinct with Integers The following code sample demonstrates using the Stream.distinct with an Integer List: List<Integer> input = Arrays.asList(3,12,11,45,12,5,3,9,20,11,3);System.out.print("Input:");input.forEach(num -> System.out.print(num+" "));System.out.println();System.out.print("Output:");List<Integer> distinctInput = input.stream().distinct().collect(Collectors.toList());distinctInput.forEach(num -> System.out.print(num+" ")); So first, the code invokes the stream method on the input List. Then, the code invokes the distinct method to obtain un...

How to find the number of years between two Dates

Prior to Java 8, you had to write complex logic to find the number of years between two dates. The DateTime API introduced from Java 8 onwards provides some methods that let you easily find the number of years between two dates. Edit The following code demonstrates this: public static void main(String[] args) { LocalDate date1 = LocalDate.parse("1997-04-28"); LocalDate date2 = LocalDate.parse("2015-11-25"); Period period = date1.until(date2); int yearsBetween = period.getYears(); System.out.println("yearsBetween:"+yearsBetween);} Java 8 has added a LocalDate class to represent a Date. So in this code, both the input Dates are held within LocalDate objects. There is a method called until on the LocalDate class. This returns a Period instance. Period has a method called getYears which returns the number of years. So this code prints the following output: yearsBetween:18

Java 8 BinaryOperator Example

In this blog post, I will be explaining how the Java 8 BinaryOperator functional interface works. To know more about functional interfaces, you can refer to  this  blog post. Edit What is BinaryOperator The BinaryOperator is a specialization of the BiFunction interface that accepts 2 arguments. However, unlike the BiFunction it accepts 2 arguments of the same data type and returns a result of the same data type. The BinaryOperator internally uses the BiFunction.apply method. BinaryOperator Interface Example with Integer data type Consider the following code snippet: BinaryOperator<Integer> additionCalculator = (a, b) -> a +b;int input1 = 6;int input2 = 5;System.out.println("Result of adding " + input1 + " and " + input2 + " is " + additionCalculator.apply(input1, input2));   Here, we have written a BinaryOperator implementation that operates on Integer data type. It accepts two integer values, adds them and returns the result. The BiFu...

Java 8 DoubleFunction Example

In this blog post, I will be explaining how the Java 8 functional interface DoubleFunction works. To know more about functional interfaces, you can refer  this  blog post. Edit The   DoubleFunction interface provides a method called apply . It accepts a single parameter of double data type. It returns a result of any data type. So it basically applies the logic in the apply method to the input parameter and returns the result. The DoubleFunction interface is a specialization of the Function interface. While the Function interface accepts any data type, the DoubleFunction interface accepts a long value. To see an example of the Function interface, refer to  this  blog post. DoubleFunction Interface that returns an Integer Consider the following code snippet: DoubleFunction<Integer> integerRetriever = input -> new Double(input).intValue();Double input = 4.8;System.out.println("Integer Value "+integerRetriever.apply(input) );   Here, we have written a   Doubl...

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...

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...

Java 8 LongConsumer example

In this blog post, I will be explaining how the Java 8 functional interface LongConsumer works. To know more about functional interfaces, you can refer this blog post. Edit The LongConsumer interface provides a method called accept . It accepts a single parameter of long data type. It does not return anything, it returns a void. So it operates via side effects i.e. it modifies the parameter passed in.The LongConsumer interface is a specialization of the Consumer  interface. While the Consumer interface accepts any data type, the LongConsumer interface accepts a long value. To see an example of the Consumer interface, refer to  this  blog post. LongConsumer Example Consider the following code snippet: public class LongConsumerDemo { public static void main(String args[]) { LongConsumer decrementBy5 = (num) -> System.out.println("Input:"+num+", Incremented Value:"+(num-5)); decrementBy5.accept(12); decrementBy5.accept(23); }}   Here, the Lon...

Java 8 Stream API map method with examples

In this blog post, I will be demonstrating the Java 8 Stream API map method. In order to understand the Stream API in detail, refer to this  blog post. Edit Introduction The map method in the Stream API can be applied on an existing Stream. It applies some logic to each element in the input stream and produces an output stream. For example, if there is an integer stream, you can you the map operation to multiply each element by 5. Or if you have a Stream of String values, you can use the map operation to convert each element in the Stream to uppercase. The map operation accepts a Function instance which is an in-built functional interface. Refer this blog post for a detailed Function example. Code Sample with Integer Consider the following code sample: public class MapIntegerDemo { public static void main(String[] args) { List<Integer> input = Arrays.asList(5, 3, 11, 15, 9, 2, 5, 11); System.out.println("Input list:"); input.forEach(num -> System.ou...

Java 8 IntConsumer Interface

In this blog post, I will be explaining how the Java 8 functional interface IntConsumer works. To know more about functional interfaces, you can refer this blog post. Edit The IntConsumer interface provides a method called accept. It accepts a single parameter of int data type. It does not return anything, it returns a void. So it operates via side effects i.e. it modifies the parameter passed in. The  IntConsumer interface is a specialization of the Consumer interface. While the Consumer interface accepts any data type, the  IntConsumer interface accepts an Integer value. To see an example of the Consumer interface, refer to  this  blog post. IntConsumer Example Consider the following code snippet: public class IntConsumerDemo { public static void main(String args[]) { IntConsumer incrementby5 = (num) -> System.out.println("Input:"+num+", Incremented Value:"+(num+5)); incrementby5.accept(12); incrementby5.accept(23); }}   Here, the IntConsumer....

Java 8 DoubleConsumer example

In this blog post, I will be explaining how the Java 8 functional interface DoubleConsumer works. To know more about functional interfaces, you can refer this blog post. Edit The DoubleConsumer interface provides a method called accept. It accepts a single parameter of double data type. It does not return anything, it returns a void. So it operates via side effects i.e. it modifies the parameter passed in. The  DoubleConsumer  interface is a specialization of the Consumer interface. While the Consumer interface accepts any data type, the DoubleConsumer interface accepts a Double value. To see an example of the Consumer interface, refer to  this  blog post. DoubleConsumer Example Consider the following code snippet: public class DoubleConsumerDemo { public static void main(String args[]) { DoubleConsumer squareGenerator = (num) -> System.out.println(num*num); double input = 5.0; squareGenerator.accept(input); }}   Here, the DoubleConsumer.accept method accepts a...