Thursday, 18 May 2023

Java hashmap to json string

There are several ways to convert a Java HashMap to a JSON string. Here are two of the most common methods:

Using Gson

Gson is a popular Java library for converting Java objects to and from JSON. To convert a HashMap to a JSON string using Gson, you can use the following code:

import com.google.gson.Gson;

public class Main {

  public static void main(String[] args) {
    // Create a HashMap.
    HashMap<String, String> map = new HashMap<>();
    map.put("name", "John Doe");
    map.put("age", "30");

    // Create a Gson object.
    Gson gson = new Gson();

    // Convert the HashMap to a JSON string.
    String json = gson.toJson(map);

    // Print the JSON string.
    System.out.println(json);
  }
}

The output of the above code will be the following JSON string:

{
  "name": "John Doe",
  "age": "30"
}

Using Jackson

Jackson is another popular Java library for converting Java objects to and from JSON. To convert a HashMap to a JSON string using Jackson, you can use the following code:

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

  public static void main(String[] args) {
    // Create a HashMap.
    HashMap<String, String> map = new HashMap<>();
    map.put("name", "John Doe");
    map.put("age", "30");

    // Create an ObjectMapper object.
    ObjectMapper mapper = new ObjectMapper();

    // Convert the HashMap to a JSON string.
    try {
      String json = mapper.writeValueAsString(map);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }

    // Print the JSON string.
    System.out.println(json);
  }
}

The output of the above code will be the same as the output of the previous code.

Java convert a date string to a date format

To convert a Java date string to a date format, you can use the following steps:

  1. Create a SimpleDateFormat object with the desired date format.
  2. Use the parse() method to parse the date string into a Date object.
  3. Use the format() method to format the Date object into a new date string with the desired format.

For example, the following code converts a date string in the format "MM/dd/yyyy" to a date string in the format "yyyy-MM-dd":

import java.text.SimpleDateFormat;

public class Main {

  public static void main(String[] args) {
    // Create a SimpleDateFormat object with the desired date format.
    SimpleDateFormat dateFormat1 = new SimpleDateFormat("MM/dd/yyyy");

    // Create a date string in the format "MM/dd/yyyy".
    String dateString1 = "05/18/2023";

    // Parse the date string into a Date object.
    Date date1 = dateFormat1.parse(dateString1);

    // Create a SimpleDateFormat object with the desired date format.
    SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");

    // Format the Date object into a new date string with the desired format.
    String dateString2 = dateFormat2.format(date1);

    // Print the new date string.
    System.out.println(dateString2);
  }
}

The output of the above code will be the following date string:

2023-05-18

Java arraylist to json string

There are several ways to convert an ArrayList to a JSON string in Java. Here are two of the most common methods:

Using Gson

Gson is a popular Java library for converting Java objects to and from JSON. To convert an ArrayList to a JSON string using Gson, you can use the following code:

Code snippet
import com.google.gson.Gson;

public class Main {

public static void main(String[] args) {
// Create an ArrayList of strings.
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");

// Create a Gson object.
Gson gson = new Gson();

// Convert the ArrayList to a JSON string.
String json = gson.toJson(list);

// Print the JSON string.
System.out.println(json);
}
}

The output of the above code will be the following JSON string:

Code snippet
[
"Hello",
"World"
]

Using Jackson

Jackson is another popular Java library for converting Java objects to and from JSON. To convert an ArrayList to a JSON string using Jackson, you can use the following code:

Code snippet
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

public static void main(String[] args) {
// Create an ArrayList of strings.
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");

// Create an ObjectMapper object.
ObjectMapper mapper = new ObjectMapper();

// Convert the ArrayList to a JSON string.
try {
String json = mapper.writeValueAsString(list);
} catch (JsonProcessingException e) {
e.printStackTrace();
}

// Print the JSON string.
System.out.println(json);
}
}

The output of the above code will be the same as the output of the previous code.

Java array to arraylist

There are several ways to convert an array to an ArrayList in Java. Here are three of the most common methods:

Using Arrays.asList()

The Arrays.asList() method is the simplest way to convert an array to an ArrayList. It takes an array as its only argument and returns a List object that contains the elements of the array.

For example, the following code converts an array of strings to an ArrayList of strings:

Code snippet
String[] array = { "Hello", "World" };
List<String> list = Arrays.asList(array);

The list object returned by Arrays.asList() is backed by the original array. This means that if you modify the original array, the changes will be reflected in the list object.

Using Collections.addAll()

The Collections.addAll() method is another way to convert an array to an ArrayList. It takes two arguments: a List object and an array. The method adds all of the elements of the array to the List object.

For example, the following code converts an array of strings to an ArrayList of strings:

Code snippet
String[] array = { "Hello", "World" };
List<String> list = new ArrayList<>();
Collections.addAll(list, array);

The advantage of using Collections.addAll() over Arrays.asList() is that you can create a new ArrayList object and then add the elements of the array to it. This gives you more control over the type of List object that is created.

Using an iteration loop

The third way to convert an array to an ArrayList is to use an iteration loop. This method is the most flexible, but it is also the most time-consuming.

To convert an array to an ArrayList using an iteration loop, you first need to create a new ArrayList object. Then, you need to iterate through the array and add each element to the ArrayList object.

For example, the following code converts an array of strings to an ArrayList of strings:

Code snippet
String[] array = { "Hello", "World" };
List<String> list = new ArrayList<>();
for (String element : array) {
  list.add(element);
}

This method is the most flexible because you can use it to convert any type of array to any type of List object. However, it is also the most time-consuming because you need to iterate through the entire array.

Tuesday, 9 May 2023

Why Should an Object Used As the Key should be Immutable

Question) Why Should an Object Used As the Key should be Immutable? 
This is another follow-up to the previous core Java interview questions. It's good to test the depth of technical knowledge of candidate by asking more and more question on the same topic. If you know about Immutability, you can answer this question by yourself. The short answer to this question is key should be immutable so that hashCode() method  always return the same value.

Since hash code returned by hashCode() method depends on upon the content of object i.e. values of member variables. If an object is mutable than those values can change and so is the hash code. If the same object returns different hash code once you inserted the value in HashMap, you will end up searching in different bucket location and will not able to retrieve the object. That's why a key object should be immutable. It's not a rule enforced by the compiler but you should take care of it as an experienced programmer.