Java Coding Problems and Tricky Solutions
Suresh Kumar Mahto
Technical Architect l AWS Certified Architect | Hi-tech Engineering
How to iterate and modify value in a Map
There are many ways to iterate the modify the value of a Map, here is a program to update and 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("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("Java", (key, value) -> "Joshua Bloch");
????? //Only modify if key doesn't exist in the map
????????????? map.computeIfAbsent("CoreJava", (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 Kin
CoreJava=Kathy Sierra
Pro Angular=Freeman
Java=Joshua Bloch
Pro Spring Boot=Felipe Gutierrez
Spring in Action=Craig Wallsg
How to print keys & values of a Map
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()
// Using an iterato
????????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);r
How to convert String to Date Object?
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
Sun Nov 13 07:45:30 IST 2022
2022-11-13
2022-11-13T19:45:30
2022-11-13T19: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", "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
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", "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 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?
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?
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 ' ' :
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' : 11
How to find next/previous(tomorrow/yesterday) date
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);
}
Thanks