Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Put Value to a Property List in Java



In this article, we will learn how to use the Properties class in Java to store and display key-value pairs. The Properties class is useful for handling configuration settings or storing data in a structured way, where both keys and values are strings. By using the put() method, we can easily add values to a property list and later retrieve or display these key-value pairs. This approach provides a simple and efficient way to manage data in a key-value format in Java applications.

Problem Statement

A properties list contains country-year pairs. Write a Java program to store values in a property list and display the key-value pairs.

Input

Initial Property List =
("India", "1983"), ("Australia", "1987"), ("Pakistan", "1992"), ("Srilanka", "1996")

Output
Initial Property List =
Srilanka / 1996
Pakistan / 1992
Australia / 1987
India / 1983

Steps to put values into a properties list and display them

The following are the steps to sort a list of properties placing nulls:

  • Import the Properties and Set classes from the java.util package.
  • Create a Properties object to store key-value pairs.
  • Use the put() method to insert country-year pairs into the property list.
  • Retrieve the keys using keySet() and iterate through them to display the key-value pairs.

Java program to put values into a Properties list

The following is an example of putting values into a Property list

import java.util.Properties;
import java.util.Set;

public class Demo {
   public static void main(String args[]) {
      Properties p = new Properties();
      p.put("India", "1983");
      p.put("Australia", "1987");
      p.put("Pakistan", "1992");
      p.put("Sri Lanka", "1996"); 
      
      Set<Object> s = p.keySet(); 

      for (Object record : s) {
         System.out.println(record + " / " + p.getProperty((String) record));
      }
   }
} 

Output

Srilanka / 1996
Pakistan / 1992
Australia / 1987
India / 1983

Code Explanation

The code creates a Properties object called p and fills it with key-value pairs that show countries and the years they won the World Cup using the put() method. To display this information, it gets the list of keys using keySet() and uses a for loop to go through each key. Inside the loop, it uses the getProperty() method to get the year for each country and prints it out in the format "country/year."

Updated on: 2024-10-30T18:44:44+05:30

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements