Posts

Showing posts with the label Java8

Parallel Streams in Java with code samples

In my earlier article, I had covered the Stream API in depth. In this article, we will be taking a look at parallel streams. Simply speaking, a parallel stream is a stream that operates on its elements in parallel. How to obtain a parallel stream Just like the stream method, all the Collection interfaces have a parallelStream method. This returns a parallel stream on the underlying Collection. Consider the following code: List<String> food = Arrays.asList("Pizza","Sandwich","Burger","Rice");Stream<String> foodStr = food.parallelStream(); This code first creates a String List food with some values. It then invokes the parallelStream method on food. This returns a String Stream which is a parallel stream. In addition, the Stream interface also has a method parallel . If the stream on which this method is invoked is a sequential stream, it returns a parallel stream corresponding to it. If the stream on which it is invoked in a paral...

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

Java 8 Comparator Changes

Java 8 has made many improvements to the Comparator interface. In this article, I will be explaining the Java 8 Comparator changes. Edit Comparator.compare From Java 8 onwards, Comparator is designated as a functional interface. So, you can implement the Comparator.compare method via a lambda expression . Consider the following Book class: public class Book { String name; int numPages; public Book(String name, int numPages) { this.name = name; this.numPages = numPages; } //getters and setters} And suppose you have a List of Book objects which needs to be sorted on the basis of the numPages field. Prior to Java 8, you had to create a class that implements the Comparator interface and use it to sort the Book List. The following code demonstrates this: public class BookCompartor implements Comparator<Book> { public int compare(Book book1, Book book2) { return book1.getNumPages() - book2.getNumPages(); }}public class ComparatorBeforeJava8Demo { public sta...

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

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

New Java 8 Features Overview with explanations

Though I’ve covered many Java 8 new features, I’ve never really given an overview of all the new features as a whole. So I will be covering that in this article. Edit Functional Interfaces Functional interfaces are simply interfaces with just one abstract method. Java 8 has introduced the @FunctionalInterface annotation that designates an interface as a functional interface. Functional Interfaces and Lambda expressions go hand in hand. Java 8 has also added some built-in functional interfaces like Predicate, Consumer, Supplier, etc. You can read more about Functional interfaces here . Lambda expressions The most talked-about feature in Java 8 is lambda expressions . Java is an object-oriented language, however, object-oriented code sometimes tends to be lengthy and verbose. Java 8’s lambda expressions enable programmers to overcome this issue by writing code as functions . This gets rid of a lot of boilerplate code and helps to keep things clean. Lambda expressi...

Java 8 Optional Explained with code samples

Java 8 has introduced a bunch of new features. The Optional feature introduced by Java 8 helps in avoiding unexpected exceptions. In this article, I will be covering this feature in detail. Edit Optional Introduction An optional can be used to represent a value that can either be present or absent. Many times methods return a null value. If the code that invokes the method expects a non-null value, this can result in a NullPointerException . To avoid this, you need to add explicit null checks in your code. This can make the code difficult to read. Consider the following code: Person person = new Person();if(person != null){ // Null Check String name = person.getName();} The above code needs to have an explicit null check for Person object. Only if the person object is not null, the code invokes the getName method. Java 8 Optionals help to avoid explicit null checks like this. So you can re-write the above code using an Optional as follows: Optional<Person> person = Option...

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

How to find the day of the week represented by a particular date

In this article, I will be demonstrating how you can find the day of the week represented by a particular date. You can use Java 8 LocalDate class for this. The following code demonstrates this: LocalDate date = LocalDate.now();DayOfWeek dayOfWeek = LocalDate.of(2019, 8, 11);System.out.println("dayOfWeek="+dayOfWeek); The LocalDate class has a method called getDayOfWeek. This returns a DayOfWeek enum which corresponds to the day of the week.  Here a LocalDate object corresponding to 11th August 2019 is created which corresponds to a Sunday. So when you execute this code, it prints the following output: dayOfWeek=SUNDAY

Java 8 Map compute methods with code samples

In this article, I will be covering the Java 8 Map compute methods.Java 8 has introduced the Map.compute, Map.computeIfPresent example, and Map.computeIfAbsent methods. Edit compute The compute method computes a new value for a particular key and updates the Map with the new value. Even if the specified key is not present in the map, it computes the value for the key and adds the key-value mapping to the Map . The following code demonstrates this: Map <Integer,String> students = new HashMap<Integer,String>();students.put(100, "Swati Shashtri");students.put(101, "Gina George");students.put(102, "Puja Khanna"); students.compute(100, (key,value) -> value+",Pune");System.out.println(students.get(100));students.compute(101, (key,value) -> value+",Bangalore");System.out.println(students.get(101));   Here, there is a Map that has a student id as the key and student name as the value. There are 3 entries in the Map...

Java 8 SplitIterator Explained with code samples

Another new feature in Java 8 is the SplitIterator interface. This article will explain what a SplitIterator is and how you can use it. Edit What is a SplitIterator? Just like a normal Iterator, you can use a SplitIterator to iterate over the elements in a Collection. A new method called splitIterator has been added to all the Collection interfaces. This returns a SplitIterator instance. The following code demonstrates this: public class SplitIteratorDemo { public static void main(String[] args) { List<Integer> input = Arrays.asList(5, 3, 21, 15, 9, 2, 12, 11); Spliterator<Integer> sitr1 = input.spliterator(); sitr1.forEachRemaining(num -> System.out.println(num)); }} The above code obtains a SplitIterator over the input list. Just like the Iterator interface, the forEachRemaning method is also available on the SplitIterator interface. This can be used to iterate through the elements in the input collection. So when you execute the above code, it pri...

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

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