Java Coding Interview Questions Core Java Interview java by devs5003 - May 25, 2021February 18, 20234 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‘. Table of Contents How to iterate and modify value in Java 8 in a Map?OutputHow to print keys & values of a Map in Java 8 ?How many ways are there to print keys & values of a Map ?How to convert String to Date Object in Java 8 ?Output How many ways are there to initialize a Set ?How to create various collections using Factory Method of Java 9 ?How to retrieve values from Set in Java 8 ?How to iterate a Map containing a List of String in Java 8 ?Output How to count occurrences of each character of a String in Java 8?OutputHow to find next/previous(tomorrow/yesterday) date in Java 8?How to remove all duplicates from an array of integers in Java using Java 8?OutputWrite a program to count the number of occurrences of a given word in a list of strings using Java 8?OutputHow to filter an array of strings by a given prefix using Java 8 Stream?Output How to iterate and modify value in Java 8 in a Map? 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 in 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: 1) Using Collection.iterator() and Iterator.forEachRemaining() map.keySet().iterator() .forEachRemaining(System.out::println); 2) Using Collection.stream() and Stream.forEach() map.values().stream() .forEach(System.out::println); 3) Using Stream.of() and Collection.toArray() and Stream.forEach() Stream.of(map.keySet().toArray()) .forEach(System.out::println); 4) Using Stream.of() and Collection.toString() and Stream.forEach() 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 in Java 8 ? Below code demonstrates the concept. Here we can convert a String to four forms of a Date. 1) String to java.util.Date 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 ? Java 9 introduced the new factory method to create immutable collections very concisely just a one-liner approach. The method name is of(…) for all the three interfaces(List, Set, Map). They have provided static methods for List, Set, and Map interfaces which take the elements as arguments and return an instance of List, Set, and Map, respectively. For example, as we can see in below code snippets, how simple, short, and concise are they! 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"); The above example creates unmodifiable collections with no generic type specified. However, we can also specify a generic type of the Collection returned by of() which will look like below: 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"); The signature of these factory methods are as below : 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 in 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 ? Let’s assume that we are writing a program of Animal Kingdom. For example, suppose that there are three categories of Animals such as Mammals, Birds & Reptiles. We will have list of some Animals in each category. Let’s consider Categories as the keys and list of animals as the values of the Map. 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? For example, let’s assume a string “JAVA PROGRAMMER”. Now, we have to count occurrences of each character in this string including spaces. We are including space also, so that we do this exercise for a sentence as well using this program. 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 in Java 8? Using Java 8 java.time.LocalDate API, we can find next/previous date. We can utilize plusDays() and minusDays() method to get the next day and the previous day, just by adding or subtracting 1 from today as shown below. We can also find the date after or before any number of days accordingly using this program. 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] Next Question will come shortly ….. Related
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 ? Reply
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); Reply