Showing posts with label java 8. Show all posts
Showing posts with label java 8. Show all posts

Thursday, 7 September 2023

Sort a List in Ascending and Descending Order Using the Java 8 Stream API

        In one of my previous posts, I covered several Java 8 Stream API coding questions and answers. In this post, we will discuss one of the most commonly asked coding interview questions: how to sort a list in ascending and descending order using the Java 8 Stream API.

1) Sort a List of Strings in Ascending Order Using the Java 8 Stream API

import java.util.Arrays;
import java.util.List;

public class SortExample {

    public static void main(String[] args) {

	 List<String> listOfStrings = Arrays.asList("A", "E", "B", "C");

         listOfStrings.stream().sorted().forEach(s -> System.out.println(s));
    }

}

Output:- A
              B
              C
              E

2) Sort a List of Strings in Descending Order Using the Java 8 Stream API

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class SortExample {

     public static void main(String[] args) {

	  List<String> listOfStrings = Arrays.asList("A", "E", "B", "C");

          listOfStrings.stream().sorted(Comparator.reverseOrder())
                                              .forEach(s -> System.out.println(s));
     }

}

Output:-   E
                C
                B
                A

3) Sort a List of Custom Java Objects (Employee Class) in Ascending or Descending Order Using the Java 8 Stream API

Employee.java,
public class Employee {
	
	private Long id;
	private String firstName;
	private String lastName;
	private String address;
      
        //constructor, setter and getter
       // and toString metghod
}

SortExample.java,
package com.main;

import java.util.ArrayList;
import java.util.List;

public class SortExample {

     public static void main(String[] args) {
		
	 Employee e1 = new Employee(1L, "Anil", "Nivargi", "XYZ");
	 Employee e2 = new Employee(2L, "Mahesh", "Nivargi", "XYZ");

	 List<Employee> employeeList = new ArrayList<>();
	 employeeList.add(e1);
	 employeeList.add(e2);
		
	  System.out.println("Sort a list in ascending order using firstName -");
		
	  //sort a list in ascending order using firstName
	  employeeList.stream().sorted((s1,s2) -> 
                        s1.getFirstName().compareTo(s2.getFirstName())).forEach(
                                 s -> System.out.println(s));
		
	  System.out.println("Sort a list in descending order using firstName -");
		
	    //sort a list in descending order using firstName
	  employeeList.stream().sorted((s1,s2) -> 
                        s2.getFirstName().compareTo(s1.getFirstName())).forEach(
                                 s -> System.out.println(s));

     }

}

Output:- 
Sort a list in ascending order using firstName -
Employee [id=1, firstName=Anil, lastName=Nivargi, address=XYZ]
Employee [id=2, firstName=Mahesh, lastName=Nivargi, address=XYZ]
Sort a list in descending order using firstName -
Employee [id=2, firstName=Mahesh, lastName=Nivargi, address=XYZ]
Employee [id=1, firstName=Anil, lastName=Nivargi, address=XYZ]

Thank you reading the blog post.

Reference Posts:-

Thursday, 24 August 2023

Find Duplicate Elements in a List Using the Java 8 Stream API

       In this post, we need to have a look one of the important coding interview questions asked for java 8 streams. Given list contains either String or Integers. Refer all coding questions here

1) Print duplicate elements using frequency and toSet methods    . 

      In the below code used Collections.frequency to filter the data with occurance value greater than 1 and toSet method used to remove the duplicated in output.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Java8StreamEx {

    public static void main(String[] args) {

	 List<Integer> integerList = Arrays.asList(2, 3, 3, 5, 6, 6, 6);

	 Set<Integer> list = integerList.stream().filter(
			        s -> Collections.frequency(integerList, s) > 1)
                                  .collect(Collectors.toSet());
		
	 list.stream().forEach(s -> System.out.println("Duplicate element - "+s));
     }
}

Output:- Duplicate element - 3
              Duplicate element - 6

2) Using frequency and toMap method(map used to store element with occurance)

Used frequency and toMap method to store duplicates into the Map with occurance as a value.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Java8StreamEx {

    public static void main(String[] args) {

	 List<Integer> integerList = Arrays.asList(2, 3, 3, 5, 6, 6, 6);

		// store duplicate into the map
	  Map<Integer, Long> map = 
                         integerList.stream().filter(
	                    s -> Collections.frequency(integerList, s) > 1).collect(
			    Collectors.toMap(Function.identity(), v -> 1L, Long::sum));

		map.entrySet().stream().forEach(s -> System.out.println(s));
	}
}

Output: - 3=2
               6=3

3) Using groupingBy and counting methods - group the similar elements and to find the occarance used counting.

To write the code to find the duplicate using groupingBy,

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Java8StreamEx {

     public static void main(String[] args) {

          List<String> listOfString = Arrays.asList("A", "B", "C", "A", "A", "D", "B");

	  Map<String, Long> mapOfStrings = 
			listOfString.stream().filter(
			    s -> Collections.frequency(listOfString, s) > 1)
			    .collect(Collectors.groupingBy(Function.identity(), 
			        Collectors.counting()));

	   mapOfStrings.entrySet().stream().forEach(s -> System.out.println(s));
    }
}

Output:-A=3
             B=2


Thank you for visiting blog.

Refer the post for coding questions - coding questions

Monday, 13 May 2019

Java 8 BiConsumer, BiFunction, and BiPredicate Interfaces with Examples

         In earlier posts, we discussed the Java 8 Consumer interface, method references, and the forEach() method with examples. In this post, we will discuss the BiConsumer, BiFunction, and BiPredicate interfaces with examples.

These functional interfaces accept two input parameters. BiConsumer performs an operation without returning a result, BiFunction accepts two inputs and returns a result, and BiPredicate accepts two inputs and returns a boolean value. We will discuss each interface in detail below.


  • BiConsumer (java.util.function package)

         BiConsumer is a functional interface that contains a single abstract method, accept(), similar to the Consumer interface. The main difference is that the Consumer interface accepts a single input parameter, whereas the BiConsumer interface accepts two input parameters. Neither interface returns a result.

Example:-

package com.test;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class BiConsumerExample {
 
         public static void main(String[] args) {
      
                   //Consumer example
                  Consumer<String> strConsumer = str -> System.out.println(str);
                  strConsumer.accept("Java Wolrd");
  
                  //BiConsumer example
                  Map<String, String> map = new HashMap<String, String>();
                  map.put("Hello", "World");
                  BiConsumer<String, String> consumer = (key, value) -> System.out.println("Key - "+ key+", Value - "+value);
    
                  map.forEach(consumer);
         }

}

Output:-
Java World
Key - Hello, Value - World
  • BiFunction (java.util.function package)
         BiFunction interface is also similar to Function interface(It is also functional interface), difference is Function interface will accept one parameter but BiFunction interface accepts two parameters as a input and returns results.

Declaration:-

Interface BiFunction<T,U,R>

Here, 

T - the type of the first argument as input
U - the type of the second argument as input
R - the type of the result of the function

Example:-

package com.test;

import java.util.function.BiFunction;
import java.util.function.Function;

public class BiFunctionExample {
 
         public static void main(String[] args) {
  
                 //Function example
                Function<Integer, Integer> printNumber = a -> a*10;
                System.out.println("Number is "+printNumber.apply(10));
  
                 //BiFunction example
                BiFunction<Integer, Integer, Integer> add = (a, b) -> a+b;
                System.out.println("Summation of two number is "+add.apply(3,2));
        }

}

Output:-
Number is 100
Summation of two number is 5
  • BiPredicate (java.util.function package)
        This interface also similar to Predicate interface and it's also functional interface. Predicate interface takes one agrument as input and return boolean value. But BiPredicate interface takes two arguments as input and returns boolean data type same as Predicate interface.

Example:-

package com.test;

import java.util.function.BiPredicate;
import java.util.function.Predicate;

public class BiPredicateExample {
 
         public static void main(String[] args) {
                
                 //Predicate example
                Predicate<String> pr = a -> a.contains("A");
                System.out.println(pr.test("Anil"));
  
                 //BiPredicate example
                BiPredicate<Integer, Integer> biPrdt = (a,b) -> a>10 && b<5;
                System.out.println(biPrdt.test(11, 2));
         }
}

Output:-
true
true


Thank you for visiting the blog.

Wednesday, 8 May 2019

Method References in Java 8

        In the previous post, we learned about the Java 8 Consumer interface with examples. In this post, we will discuss another important feature introduced in Java 8: method references.

A method reference is a shorthand syntax for a lambda expression that invokes an existing method. In earlier versions of Java, we invoked a method using the dot (.) operator on an object. In Java 8, the :: operator can be used to refer to a method directly, making the code more concise and readable.

The following is the general syntax of a method reference:

Object :: methodName

The example of Method Reference uses,

Using lambda expression,


s -> System.out.println(s)

It replaces using method reference as below,

System.out::println

Examples:-

1)  Instance method of object example(Object::instanceMethod)

MethodRefExample.java,

package com.test;

interface MethodRefInterface {  
       void abstractMethod();  
} 
 
public class MethodRefExample {
  
           public void method(){  
                   System.out.println("This is a method reference example");  
           }  

           public static void main(String[] args) {
                    MethodRefExample methodRef = new MethodRefExample();  
                    MethodRefInterface ref= methodRef::method;
                    ref.abstractMethod();
           }  
}  

Output:- 

This is a method reference example.



2) Static method of a Class(ClassName::methodName)

MethodRefStatic.java,


package com.test;

import java.util.Arrays;
import java.util.List;

public class MethodRefStatic {
 
         public static void main(String[] args) {
                   List<Integer> list = Arrays.asList(1, 2, 3, 4);
                   System.out.println("Using lambda expression");
                   list.forEach(num -> printNumbers(num));  //using lambda expression
                   System.out.println("Using method references");
                   list.forEach(MethodRefStatic::printNumbers); //using method references
         }
 
         public static void printNumbers(int number) {
                   System.out.println("Number - " + number);
         }
}

Output:-
Using lambda expression
Number - 1
Number - 2
Number - 3
Number - 4
Using method references
Number - 1
Number - 2
Number - 3
Number - 4


3) Example of method reference to a Constructor(Class::new)

MethodRefConstruct.java,


package com.test;

interface MessageInterface{  
         MethodRefEx getMessage(String msg);  
} 

class MethodRefEx {
 
         MethodRefEx(String msg){  
                  System.out.print(msg);  
         }  
}  
class MethodRefConstruct {  
     
         public static void main(String[] args) {  
                   MessageInterface msg = MethodRefEx::new;  
                   msg.getMessage("Hello World");  
         }  
}  

Output:-
Hello World



Related Posts:--
1) Java 8 - Consumer Interface with examples
2) Java 8 forEach method with examples
3) Java 8 features with examples

Monday, 6 May 2019

Java 8 - Consumer Interface with examples

        In the current post, I will explain you the in-built functional interface Consumer introduced in Java 8 with examples. It contains two methods accept() & andThen(), comes under java.util.function package.

What is java.util.function.Consumer ?

       Consumer<T> is an in-built functional interface introduced in Java 8 and it is in the java.util.function package.  Here T is any type of input arguments. Consumer can be used in all contexts where an object needs to be consumed, i.e it will take argument as an input and some operation needs to be performed on the object without returning any result.  

       This is a functional interface because it contains only one abstract method i.e accept().


Methods in Consumer Interface
  • accept()
  • andThen()

       The accept() method is abstract method, need to implement in the code, it will take one parameter as argument and doesn't return anything.

syntax:-

    void accept(T t);

The following example shows how to use the accept() method of the Consumer interface.

package com.test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerInterface {
 
       public static void main(String[] args) {
  
               List<Integer> values = Arrays.asList(2,3,5,8);
               Consumer<Integer> printInt = new Consumer<Integer>() {
                        @Override
                        public void accept(Integer var) {
                                  System.out.println("Number - "+var);
                        }  
               };
  
               //print the single integer number using consumer interface.
               printInt.accept(10);
  
               //print the integers using consumer interface
               values.forEach(printInt);
       }

}

Output:--
Number - 10
Number - 2
Number - 3
Number - 5
Number - 8



andThen() -   is a default method in Consumer interface. Method andThen(), when applied on a Consumer interface, takes as input another instance of Consumer interface and returns as a result a new consumer interface which represents aggregation of both of the operations defined in the two Consumer interfaces.

syntax:-


default Consumer <T> 
        andThen(Consumer<? super T> after)

The return type of the above method is Consumer and this accepts a parameter after which is the Consumer to be applied after the current one.

The below code is to illustrate the andThen() method,


package com.test;

import java.util.function.Consumer;

public class ConsumerInterface {
 
      public static void main(String[] args) {
  
              Consumer<String> cons1 = str -> {
                        System.out.println(str + " World");
              };
      
              Consumer<String> cons2 = str -> {
                        System.out.println(str + " Java");
              };
  
              cons1.andThen(cons2).accept("Hello");
      }

}

Output:-

Hello World
Hello Java




Related Posts:-
1) Java 8 forEach method with examples
2) Java 8 features with examples

Tuesday, 9 April 2019

Java 8 forEach method with examples

        In this post, we will discuss or learn how to iterate the Map, List and Stream in java 8 using forEach method. I have given some sample examples of each collection.

  • Java 8 forEach method to iterate List
The below example is to iterate the list using foreach method and lambda expression in java 8.

package com.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Java8forEach {
     public static void main(String[] args) {
  
             List<String> list = new ArrayList<String>(Arrays.asList("A", "B", "C"));
  
             //Java 7, to iterate the above list
             for (String str : list) {
                   System.out.println(str);
             }
  
             //java 8, foreach method to iterate list
             list.forEach(str -> {System.out.println(str);});
     }

}

If you see the above example, you can reduce the code in Java 8 compared to earlier versions of Java.


  • Java 8 forEach method to iterate Map
In Java 8, you can iterate the map using Map.forEach(action) method and lambda expression. 

package com.test;

import java.util.HashMap;
import java.util.Map;

public class JavaforEachMap {
 
      public static void main(String[] args) {
  
           Map<Integer, String> map = new HashMap<Integer, String>();
           map.put(1, "Dell");
           map.put(2, "HCL");
           map.put(3, "Toshiba");
  
           //Java 7(earlier versions), iterate a Map
           for (Map.Entry<Integer, String> entry : map.entrySet()) {
                System.out.println("Key - "+entry.getKey() +" Value - "+entry.getValue());
           }
  
           //Java 8, iterate Map using forEach() method and lambda expression
           map.forEach((k,v) -> {
                System.out.println("key - "+k + " Value - "+v);
           });
     }

}


  • Iterate a List using Stream API and forEach() method
        In java 8, java.util.Stream represents a stream on which one or more operations can be performed. Stream operations are either intermediate or terminal. Stream terminal operations return a result of a certain type, intermediate operations return the stream itself so you can chain multiple method calls in a row. Streams are created on a source, e.g. a java.util.Collection like lists or sets (maps are not supported). Stream operations can either be executed sequential or parallel.

      Compare java 7 and earlier versions and java 8 code to iterate a list with certain conditions as follows,

package com.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Java8Stream {
 
      public static void main(String[] args) {
  
            List<String> list = new ArrayList<String>(Arrays.asList("abc", "bcd", "afd", "art"));

            //Java 7, to iterate list with some conditions
            for (String str : list) {
                 if (str.contains("a")) {
                       System.out.println(str);
                 }
            }
  
           //same example in java 8 using foreach() and stream api
           list.stream().filter(a -> a.contains("a")).forEach(str -> {
                 System.out.println(str);
           });
      }

}