Java Program to convert Properties list into a Map

Java 8Object Oriented ProgrammingProgramming

To convert Properties list into a map, let us first create an object of Properties class −

=Properties p = new Properties();

Now, use setProperty() to set key-value pair −

p.setProperty("P", "1");
p.setProperty("Q", "2");
p.setProperty("R", "3");
p.setProperty("S", "4");
p.setProperty("T", "5");
p.setProperty("U", "6");

With that, the following is how the Properties list is converted into a Map −

HashMap<String, String>map = new HashMap<String, String>((Map) p);

Example

 Live Demo

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class Demo {
   public static void main(String args[]) {
      Properties p = new Properties();
      p.setProperty("P", "1");
      p.setProperty("Q", "2");
      p.setProperty("R", "3");
      p.setProperty("S", "4");
      p.setProperty("T", "5");
      p.setProperty("U", "6");
      p.setProperty("V", "7");
      HashMap<String, String>map = new HashMap<String, String>((Map) p);
      Set<Map.Entry<String, String>>set = map.entrySet();
      System.out.println("Key and Value of the Map... ");
      for (Map.Entry<String, String>m: set) {
         System.out.print(m.getKey() + ": ");
         System.out.println(m.getValue());
      }
   }
}

Output

Key and Value of the Map...
P: 1
Q: 2
R: 3
S: 4
T: 5
U: 6
V: 7
raja
Published on 24-Apr-2019 12:39:18
Advertisements