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

Monday, 24 July 2023

Java 8 Stream Coding Interview questions and answers

      Before attending any interview need to look into the Stream coding questions beacuse Stream API is an important topic in java 8.

Below are the java 8 stream coding questions and answers.

1) Write a program to print the list of elements from a list using java 8 stream

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

public class Java8Stream {
	public static void main(String[] args) {
              List<String> list = Arrays.asList(new String[] {"ABC", "BCD", "CDE"});
	      list.stream().forEach(s -> System.out.println(s));
	}
}

Output:- ABC
              BCD
              CDE

2) Write a program to convert lowercase string element of a list into uppercase.

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

public class Java8Stream {
     public static void main(String[] args) {
	   List<String> list = Arrays.asList(new String[] {"Abc", "bcd", "cde"});
	   list.stream().map(s-> s.toUpperCase()).forEach(
				s -> System.out.println(s));
     }
}

Output:- ABC
              BCD
              CDE

3) Print a list of strings those start with letter "A" and return updated list.

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

public class Java8Stream {
	public static void main(String[] args) {
		List<String> list = Arrays.asList(new String[] {"Abc", "bcd", "cde"});
		List<String> updatedList = list.stream().filter(s-> s.startsWith("A"))
				.collect(Collectors.toList());
		updatedList.stream().forEach(s -> System.out.println(s));
	}
}

Output:- Abc

4) Write a code to calculate the summation of the integers from the list.

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

public class Java8Stream {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(new Integer[] {1,2,3, 4,5});
		//Using lambda expression
		Integer sum = list.stream().mapToInt(i -> i).sum();
		System.out.println(sum);
		
		//Using Integer valueOf method
		Integer sumOfIntegers = list.stream().mapToInt(Integer::valueOf).sum();
		System.out.println(sumOfIntegers);
		
		//Using Integer intValue method
		Integer sumOfIntegerValue = list.stream().mapToInt(Integer::intValue).sum();
		System.out.println(sumOfIntegerValue);	
	}
}

Output:- 15
              15
              15

5) Create a Map object from List using Stream API

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
		List<String> list = Arrays.asList(new String[] {"Ab", "Bcd", "Ce"});
		Map<String, Integer> map = list.stream().collect(Collectors.toMap(
				s->s, s->s.length()));
		map.forEach((x,v) -> System.out.println("key - "+x+", value - "+v));
	}
}

Output:-
key - Ab, value - 2
key - Ce, value - 2
key - Bcd, value - 3

6) Write a program to list the distinct integers from list or remove duplicates from the list.

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

public class Java8Stream {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(new Integer[] {1, 2, 1,4});
		List<Integer> listWithDistinct = list.stream().distinct().collect(Collectors.toList());
		listWithDistinct.stream().forEach(s-> System.out.println(s));
	}
}

Output:-1
             2
             4

7) Write a program to find the Minimum number from a Stream/list.

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

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {1, 2,3,4});
	     Integer minNumber = list.stream().mapToInt(s->s).min().getAsInt();
	     System.out.println(minNumber);
	}
}

Output:-1

8) Write a program to find the Maximum number from a Stream/list.

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

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {1, 2,3,4});
	     Integer maxNumber = list.stream().mapToInt(s->s).max().getAsInt();
	     System.out.println(maxNumber);
	}
}

Output:-4

9) Write a program to sort the given list using java 8 stream.

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

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
	     List<Integer> sortedList = list.stream().sorted().collect(Collectors.toList());
	     sortedList.stream().forEach(s-> System.out.println(s));
	}
}

Output:-2
             3
             4
             8

10) Write a program to sort the given list in descending order using stream.

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

public class Java8Stream {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
		List<Integer> sortedList = list.stream().sorted(
				Collections.reverseOrder()).collect(Collectors.toList());
		sortedList.stream().forEach(s-> System.out.println(s));
	}
}

Output:-8
             4
             3
             2

11) Write a program to count the total number of integers in the list.

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

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
	     long count = list.stream().count();
	     System.out.println(count);
	}
}

Output:-4

12)  Convert List<List<String>> into List<String> using flatMap method.

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

public class Java8Stream {
	public static void main(String[] args) {
	     List<List<Integer>> listListOfStrings = new ArrayList<List<Integer>>();
	     List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
	     listListOfStrings.add(list);
	     //use flatMap method
	     List<Integer> newList = listListOfStrings.stream().flatMap(
				s-> s.stream()).collect(Collectors.toList());
	     newList.stream().forEach(s-> System.out.println(s));
	}
}

Output:-8
             2
             3
             4

13) Group by a list element and display the total count of the element using Collectors groupingBy method.

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

public class Java8Stream {
	public static void main(String[] args) {
	     List<String> letters = Arrays.asList("A", "B", "C","A", "D", "C", "D");
	     Map<String, Long> mapWithLetterCount = letters.stream().collect(
	                        Collectors.groupingBy(
	                                Function.identity(), Collectors.counting()));  
	     System.out.println(mapWithLetterCount);   
	}
}

Output:- {A=2, B=1, C=2, D=2}

14)  Find the first element from the given list using java 8 stream.

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

public class Java8Stream {
	public static void main(String[] args) {
	     List<String> letters = Arrays.asList("A", "B", "C","A", "D", "C", "D");
	     String firstElement = letters.stream().findFirst().orElse("Default");  
	     System.out.println(firstElement);   
	}
}

Output:-A

15)  anyMatch code example - if any one of the list element matches with given character "A" then return true.

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

public class Java8Stream {
	public static void main(String[] args) {
             List<String> letters = Arrays.asList("A", "B", "C", "D");
	     boolean foundElement = letters.stream().anyMatch(s-> s.equalsIgnoreCase("A"));  
	     System.out.println(foundElement);   
	}
}

Output:-true

16) allMatch code example - if all of the elements matches with the given element say "A" then return true else false.

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

public class Java8Stream {
	public static void main(String[] args) {
             List<String> letters = Arrays.asList("A", "B", "C", "D");
	     boolean foundMatches = letters.stream().allMatch(s-> s.equalsIgnoreCase("A"));  
	     System.out.println(foundMatches);   
	}
}

Output:-false

17) Write a program to remove the duplicates from the list using Collectors toSet method.

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

public class Java8Stream {
	public static void main(String[] args) {
	     List<String> letters = Arrays.asList("A", "B", "C", "D", "A", "B");
	     Set<String> nonDuplicateSet = letters.stream().collect(Collectors.toSet());  
	     nonDuplicateSet.stream().forEach(s-> System.out.println(s));
	}
}

Output:-A
             B
             C
             D

     
Thank you for reading the post.

Reference Posts:-

Sunday, 2 April 2017

Java Vertual Machine(JVM) Architecture in Java

    In this post, we will learn more about JVM Architecture in Java and components of JVM in detail.

What is JVM ?


       JVM is a  Java Virtual Machine and  was developed with the concept of Write Once Runs Anywhere, which runs on a Virtual Machine. The compiler compiles the Java file into a Java .class file, and then that .class file is input to the JVM, which loads and executes the class file.

JVM Architecure Design:


JVM Architecture

How does the JVM works?


     As shown in the above diagram, a JVM is divided into three main subsystems,

1)  Class Loader Subsystem
2)  Runtime Data Area
3)  Exceution Engine

1)  Class Loader subsystem 

   
      Java's dynamic class loading functionality is handled by the class loader subsystem.  It loads, links and initializes the class when it refer to the class for the first time at run time, not at compile time. It performs three major functionality such as Loading, Linking and Intialization.

1.1) Loading

    Classes will be loaded by this component. There are three class loaders which can help to load the classes at run time as BootStrap ClassLoader, Extension ClassLoader and Application ClassLoader.

  •  BootStrap ClassLoader        
       Responsible for loading the classes from the bootstrap classpath , nothing but rt.jar. Highest priority will be given to this loader

  •  Extension ClassLoader 
        Responsible for loading classes which are inside ext folder (jre/lib).

  •  Application ClassLoader
       Responsible for loading Application Level Classpath, path mentioned environment variable etc.


1.2) Linking 

  • Verify - Byte code verifier will verify if the generated byte code is proper or not. If not a proper then will get Verification error.

  •  Prepare -  For all static variables memory will be allocated and assigned with default values.
  •  Resolve - For all symbolic memory references are replace with original references from method area.

1.3)  Intialization 

 
      This is the final phase of the class loading , here all static variables will be assigned with the original values and the static block will be executed.


2) Runtime Data Area


  The Runtime Data Area is divided into 5 major components as below,    

1) Method Area 

          All the class level data will be stored here, including the static variables. There is only one method area per JVM and it's  shared resource.

2) Heap area

         All the objects and their corresponding  instance variables and Arrays will be stored here. There is only one Heap Area per JVM. Since the Method and Heap area share memory for multiple threads, data stored is not thread safe.

3)  Stack Area

        For every thread, a separate run time stack will be created. For every method call , one entry will be made in the stack  memory which is called as Stack Frame. All Local variables will be created in the stack memory. The Stack Area is a thread safe since it's not a shared resource. The Stack Area is divided into three sub entities : Local Variable Array, Operand Stack  &  Frame data.

4) PC Registers


        Each thread will have separate PC Registers, to hold the address of current executing instruction once the instruction is executed the PC Register will be updated with the next instruction


5) Native Method Stacks
   
        Native method stack holds native method information.  For every thread, a separate native method stack will be created.


3) Execution Engine

 
       The byte code which is assigned to the Runtime Data Area will be executed by the Execution Engine. The Execution Engine reads the byte code and executes the code step by step as follows,    

  •  Interpreter 
           The Interpreter interprets the byte code faster but executes slowly. The disadvantage of interpreter is that when one method is called multiple times, every time a new interpretation is required.

  •   JIT Compiler 
            The JIT Compiler neutralizes the disadvantage of the interpreter.  The Execution Engine will be using the help of interpreter in converting the byte code, but when it finds the repeated code it uses the JIT Compiler, which compiles the entire byte code and changes it to native code. This native code will be used directly for repeated method calls, which improve the performance of the system.

  •    Garbage Collector 
            Collects and removes the unreferenced objects. Garbage collection can be triggered by calling "System.gc()", but the execution is not guaranteed. Garbage collection of the JVM collects the objects that are created.

 Java Native Interface(JNI) : - 

       JNI will be interacting with the Native Method Libraries and provides the Native Libraries for the Execution Engine.

Native Method Libraries: - 

       It is a collection of the Native Libraries which is required for the Execution Engine.


Related Posts:--

Friday, 27 June 2014

Explain bean life cycle in Spring

            Spring framework is based on IOC(Inversion Of Control) so we call it as IOC container also Spring beans reside inside the IOC container. Spring beans are nothing but Plain Old Java Object (POJO).

Following steps explain their life cycle inside the container.
    
1)  Container will look the bean definition inside configuration file (e.g. bean.xml).
     
2)  Using Reflection API container will create the object and if any property is defined inside the bean definition then it will also be set.
   
3 If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.

4 If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.


5 If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called before the properties for the Bean are set.

    
6 If an init() method is specified for the bean, it will be called.

7 If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the bean reference.

     
8 If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in the Bean class will be called.