In this article, We will discuss about Java Coding Interview Questions and their Answers. Moreover, we will try to provide multiple approaches to solve a coding problem. Additionally, related concepts to a particular coding problem will also be discussed. Our primary focus of this article is to provide all kinds of Java Coding Interview Questions with their Answers. However, for theoretical questions & answers of Java Interview, kindly visit our another article โJava Interview Questionsโ.
How to iterate and modify value in a Map using Java 8?
Here is the program to update & iterate a Map in Java 8.
public class MapUpdateTest { ย ย ย ย public static void main(String[] args) { ย ย ย ย ย ย Map<String,String> map = new HashMap<String,String>(); ย ย ย ย ย ย ย map.put("Effective Java", "Kathy Sierra"); ย ย ย ย ย ย ย map.put("Spring in Action", "Craig Walls"); ย ย ย ย ย ย ย map.put("Hibernate in Action", "Gavin King"); ย ย ย ย ย ย ย map.put("Pro Angular", "Freeman"); ย ย ย ย ย ย ย map.put("Pro Spring Boot", "Felipe Gutierrez"); ย ย //Only modify if key already exists in the map ย ย ย ย ย ย map.computeIfPresent("Effective Java", (key, value) -> "Joshua Bloch"); //Only modify if key doesn't exist in the map map.computeIfAbsent("Core Java", (value) -> "Kathy Sierra"); //iterate and print the values map.entrySet().iterator() .forEachRemaining(System.out::println); } }
Output
Below is the output after executing the program.
Hibernate in Action=Gavin King Core Java=Kathy Sierra Pro Angular=Freeman Effective Java=Joshua Bloch Pro Spring Boot=Felipe Gutierrez Spring in Action=Craig Walls
How to print keys & values of a Map using Java 8 ?
As we should be aware that keySet() method returns all the keys contained in a Map as a set. The values() method returns all the values contained in a Map as a set. Hence, we should use keySet() to print all keys present in the map and values() to print all values. There are multiple ways to do that:
ย ย ย ย ย ย ย ย map.keySet().iterator() ย ย ย ย ย ย ย ย .forEachRemaining(System.out::println);
ย ย ย ย ย ย ย ย map.values().stream() ย ย ย ย ย ย ย ย .forEach(System.out::println);
ย ย ย ย ย ย ย ย Stream.of(map.keySet().toArray()) ย ย ย ย ย ย ย ย ย ย ย .forEach(System.out::println);
ย ย ย ย ย ย ย ย Stream.of(map.values().toString()) ย ย ย ย ย ย ย ย ย ย ย .forEach(System.out::println);
How many ways are there to print keys & values of a Map ?
There are multiple ways to print keys & values of a Map. Below is the list and examples of each approach.
1) Using Iterator
2) Using For-each loop
3) Using Java 8 โ Collection.iterator() and Iterator.forEachRemaining()
4) Using Java 8 โ Collection.stream() and Stream.forEach()
5) Using Java 8 โ Stream.of() andย Collection.toArray() and Stream.forEach()
6) Using Java 8 โ Stream.of() andย Collection.toString() and Stream.forEach()
ย ย ย ย // 1. Using an iterator ย ย ย ย ย ย ย ย Iterator<Integer> itr = map.entrySet().iterator(); ย ย ย ย ย ย ย ย while (itr.hasNext()) { ย ย ย ย ย ย ย ย ย ย ย ย System.out.println(itr.next()); ย ย ย ย ย ย ย ย } ย ย ย ย ย ย ย ย // Using For-each loop ย ย ย ย ย ย ย ย for (Integer key: map.entrySet()) { ย ย ย ย ย ย ย ย ย ย ย ย System.out.println(key); ย ย ย ย ย ย ย ย } ย ย ย ย ย ย ย ย // Using Java 8 โ Collection.iterator() and Iterator.forEachRemaining() ย ย ย ย ย ย ย ย map.entrySet().iterator() ย ย ย ย ย ย ย ย .forEachRemaining(System.out::println); ย ย ย ย ย ย ย ย // Using Java 8 โ Collection.stream() and Stream.forEach() ย ย ย ย ย ย ย ย map.entrySet().stream() ย ย ย ย ย ย ย ย .forEach(System.out::println); ย ย ย ย ย ย ย ย // Using Java 8 โ Stream.of() + Collection.toArray() + Stream.forEach() ย ย ย ย ย ย ย ย Stream.of(map.entrySet().toArray()) ย ย ย ย ย ย ย ย ย ย ย .forEach(System.out::println); ย ย ย ย ย ย ย ย // Using Java 8 - Stream.of() andย Collection.toString() and Stream.forEach() ย ย ย ย ย ย ย ย Stream.of(map.entrySet().toString()) ย ย ย ย ย ย ย ย ย ย ย .forEach(System.out::println);
How to convert String to Date Object using Java 8 ?
2) String to java.time.LocalDate
3) String to java.time.LocalDateTime
4) String to java.time.ZonedDateTime
import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; public class StringToDate { public static void main(String[] args) throws ParseException { //String to a java.util.Date SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a", Locale.ENGLISH); String dateInString = "24-May-2021 9:45:30 AM"; Date date = dateFormatter.parse(dateInString); System.out.println(date); //String to a java.time.LocalDate LocalDate localDate = LocalDate.parse("2021-05-24"); System.out.println(localDate); //String to a java.time.LocalDateTime LocalDateTime localDateTime = LocalDateTime.parse("2021-05-24T21:45:30"); System.out.println(localDateTime); //String to a java.time.ZonedDateTime DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z"); ZonedDateTime zonedDateTime = ZonedDateTime.parse("2021-05-24 21:45:30 America/New_York", formatter); System.out.println(zonedDateTime); } }
Output
Mon May 24 09:45:30 IST 2021 2021-05-24 2021-05-24T21:45:30 2021-05-24T21:45:30-04:00[America/New_York]
How many ways are there to initialize a Set ?
There are multiple ways to initialize a Set collection. Below is the list of some of them with examples.
1) Using Anonymous Class
Set<String> set = new HashSet<String>() {
ย ย ย ย {ย
ย ย ย ย add("California");
ย ย ย ย add("Chicago");
ย ย ย ย add("New York");
ย ย ย }
};
2) Using instance of another Collection
Set<String> set = new HashSet<>(Arrays.asList("California", "Chicago", "New York"));
3) Using Stream of Java 8
Set<String> set = Stream.of("California", "Chicago", "New York")
ย ย .collect(Collectors.toCollection(HashSet::new));
4) Using Factory Method of Java 9
Set<String> set = Set.of("California", "Chicago", "New York");
How to create various collections using Factory Method of Java 9 ?
List<String> list = List.of("USA", "Canada", "Russia");
Set<String> set = Set.of("USA", "Canada", "Russia");
Map<String, String> map = Map.of("USA", "Washington, D.C.", "Canada", "Ottawa", "Russia", "Moscow");
List<String> list = List.<String>of("USA", "Canada", "Russia"); Set<String> set = Set.<String>of("USA", "Canada", "Russia"); Map<String, String> map = Map.<String, String>of("USA", "Washington, D.C.", "Canada", "Ottawa", "Russia", "Moscow");
static <E> List<E> of(E e1, E e2, E e3)
static <E> Set<E> of(E e1, E e2, E e3)
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3) // K=Key, V=Value
How to retrieve values from Set using Java 8 ?
In order to retrieve values from a Set using Java 8, we can use Stream API of Java 8. Moreover, we must create a Stream from the Set and then iterate the Stream. For example, below code demonstrates the concept.
public class SetValuesRetrieval { public static void main(String[] args) { // Creating a Set Set<String> set = new HashSet<>(); set.add("California"); set.add("Chicago"); set.add("New York"); // Retrieving values of the Set Stream<String> stream = set.stream(); stream.forEach((element) -> { System.out.println(element); }); } }
However, if you are using JDK 9 and above version, you can even minimize the lines of code.
public class SetValuesRetrieval { public static void main(String[] args) { //Creating a Set Set<String> set = Set.of("California","Chicago","New York"); //Retrieving values of the Set set.stream().forEach(System.out::println); } }
How to iterate a Map containing a List of String in Java 8 ?
public class IterateMapOfList { public static void main(String[] args) { // Create HashMap of category and list of animals under the category Map<String, List<String>> listOfAnimals = new HashMap<String, List<String>>(); // List #1: Creating list of Animals in Mammals Category List<String> listOfMammals = Arrays.asList("Cat", "Dog", "Monkey", "Cow"); //Adding listOfMammals into Mammal's Category listOfAnimals.put("Mammals", listOfMammals); // List #2: Creating list of Animals in Birds Category List<String> listOfBirds = Arrays.asList("Crow", "Parrot", "Peacock", "Flamingo"); //Adding listOfMammals into Bird's Category listOfAnimals.put("Birds", listOfBirds); // List #3: Creating list of Animals in Reptiles Category List<String> listOfReptiles = Arrays.asList("Lizard", "Turtle", "Crocodile", "Python"); //Adding listOfMammals into Reptile's Category listOfAnimals.put("Reptiles", listOfReptiles); // Iterating Map using forEach() in Java 8 listOfAnimals.forEach( (key, value)->System.out.println( "Category name : " + key + "\t\t" + "List of Animals under the Category : " + value)); } }
Outputย
Category name : Reptilesย ย ย ย ย ย ย ย ย ย ย List of Animals under the Category : [Lizard, Turtle, Crocodile, Python] Category name : Birdsย ย ย ย ย ย ย ย ย ย ย ย ย ย List of Animals under the Category : [Crow, Parrot, Peacock, Flamingo] Category name : Mammalsย ย ย ย ย ย ย ย ย ย List of Animals under the Category : [Cat, Dog, Monkey, Cow]
How to count occurrences of each character of a String in Java 8?
public class CharactersCountTest { public static void main(String[] args) { String someString = "JAVA PROGRAMMER"; char[] strArray = someString.toCharArray(); //getting distinct characters in strArray Set<Character> set = new TreeSet<>(); for (char c : strArray){ set.add(c); } //set.forEach(System.out::println); for (char c : set) { // Using Streams & Lambda Expressions in Java 8 long count = someString.chars().filter(ch -> ch == c).count(); System.out.println("Occurances of Character '" +c+ "' : " +count); } }
Output
Occurrences of Character ' ' : 1 Occurrences of Character 'A' : 3 Occurrences of Character 'E' : 1 Occurrences of Character 'G' : 1 Occurrences of Character 'J' : 1 Occurrences of Character 'M' : 2 Occurrences of Character 'O' : 1 Occurrences of Character 'P' : 1 Occurrences of Character 'R' : 3 Occurrences of Character 'V' : 1
How to find next/previous(tomorrow/yesterday) date using Java 8?
private LocalDate getNextDay(LocalDate localdate) { ย ย ย ย return localdate.plusDays(1); } private LocalDate getPrevDay(LocalDate localdate) { ย ย ย ย return localdate.minusDays(1); }
How to remove all duplicates from an array of integers in Java using Java 8?
Below is the program:
import java.util.Arrays; public class RemoveDuplicates { public static void main(String[] args) { Integer[] array = {5, 10, 3, 7, 2, 10, 5}; Integer[] distinct = Arrays.stream(array) .distinct() .toArray(Integer[]::new); System.out.println("Distinct elements: " + Arrays.toString(distinct)); } }
Output
Distinct elements: [5, 10, 3, 7, 2]
Write a program to count the number of occurrences of a given word in a list of strings using Java 8?
Here is the program:
import java.util.Arrays; import java.util.List; public class WordCount { public static void main(String[] args) { List<String> strings = Arrays.asList("java scala ruby", "java react spring java"); String word = "java"; long count = strings.stream() .flatMap(s -> Arrays.stream(s.split(" "))) .filter(w -> w.equals(word)) .count(); System.out.println("Occurrences of \"" + word + "\": " + count); } }
Output
Occurrences of "java": 3
How to filter an array of strings by a given prefix using Java 8 Stream?
import java.util.Arrays; public class StringPrefixFilter { public static void main(String[] args) { String[] strings = {"java", "scala", "javascript", "ruby","spring","angular"}; String prefix = "j"; String[] filtered = Arrays.stream(strings) .filter(s -> s.startsWith(prefix)) .toArray(String[]::new); System.out.println("Filtered strings: " + Arrays.toString(filtered)); } }
Output
Filtered strings: [java, javascript]
ย
ย
Please give an example of no of occurence of each character in String using java 8
Dear Srikanth, Itโs now added.
Write a program using Java 8 streams to find second highest Integer in a given array of 11,13,65,76,45,98,123,100,111,44 ?
int[] integerArray = {11,13,65,76,45,98,123,100,111,44};
int secondHigest = Arrays.stream(integerArray).boxed().sorted(Comparator.reverseOrder()).limit(2).skip(1).findFirst().get();
System.out.println(โsecondHigest number is โ + secondHigest);