Showing posts with label coding interview questions. Show all posts
Showing posts with label coding interview questions. 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

Tuesday, 15 August 2023

Java program to find the Second largest number in an Array or List

     Given an unsorted array of integers or a list, write a Java program to find the second largest element.

1) Given input is an array of integers

import java.util.Arrays;

public class SecondLargest {

	public static void main(String[] args) {	
		SecondLargest secondLargest = new SecondLargest();
		int[] array = { 2, 8, 3, 4, 5, 7 };
		System.out.println("Second largest number - " + secondLargest.findSecondLargestNumber(array));
	}

	private int findSecondLargestNumber(int[] array) {
		Arrays.sort(array);
		return array[array.length - 2];
	}

}

Output :- Second largest number - 7


2) Given input is a list

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

public class SecondLargest {

	public static void main(String[] args) {

		SecondLargest secondLargest = new SecondLargest();
		List<Integer> list = Arrays.asList(new Integer[] { 2, 8, 3, 4, 5, 7 });
		System.out.println("Second largest number - " 
					+ secondLargest.findSecondLargestNumber(list));
	}

	private int findSecondLargestNumber(List<Integer> listOfIntegers) {
		Collections.sort(listOfIntegers);
		return listOfIntegers.get(listOfIntegers.size() - 2);
	}

}

Output:- Second largest number - 7

3) Given input as a List, find second largest number using Stream(Java8)

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

public class SecondLargest {

	public static void main(String[] args) {

		SecondLargest secondLargest = new SecondLargest();
		List<Integer> list = Arrays.asList(new Integer[] { 2, 8, 3, 4, 5, 7 });
		System.out.println("Second largest number - " 
					+ secondLargest.findSecondLargestNumber(list));
	}

	private int findSecondLargestNumber(List<Integer> listOfIntegers) {
		return listOfIntegers.stream().sorted()
				.skip(listOfIntegers.size() - 2)
				.findFirst()
				.get();
	}

}

Output:- Second largest number - 7.


Thank you for visiting the blog.

Related page:-