Determining If a Preference Node Contains a Specific Value

Ads
 

Determining If a Preference Node Contains a Specific Value

This section demonstrates you to determine whether the Preference code contains the specified value or not by enumerating the key/value pairs in a preference node and checks each value for a match.

This section demonstrates you to determine whether the Preference code contains the specified value or not by enumerating the key/value pairs in a preference node and checks each value for a match.

Determining If a Preference Node Contains a Specific Value

     

This section demonstrates you to determine whether the Preference code contains the specified value or not by enumerating the key/value pairs in a preference node and checks each value for a match. You can see in the given example, we have create a method containsValue(String value). This method returns the key of a preference node whose value matches the specified value. If no such key exists, it will return null. To get the node, we have used Preferences.userRoot().node("/Roseindia Employees").

node.keys()- This method get all the keys from the Preference node.

Following code scan the keys:

 

 

 

for (int i=0; i<keys.length; i++) {
if (value.equals(node.get(keys[i], null))) {
return keys[i];
}
}

Here is the code SpecificValue.java

import java.io.*;
import java.util.prefs.*;

public class SpecificValue{
  public static String containsValue(String value) {
  Preferences node = Preferences.userRoot().node("/Java Types");
  try {
  String[] keys = node.keys();
  for (int i=0; i<keys.length; i++) {
  if (value.equals(node.get(keys[i], null))) {
  return keys[i];
  }
  }
  catch (Exception e) {}
  return null;
  }
public static void main(String[]args){
SpecificValue s=new SpecificValue();
String st=s.containsValue("Hello");
System.out.println(st);
 }
}

When you run the above code, the method checks whether the Preference node 'Java Types' contains the specified value 'Hello' or not. If it finds the specified value in the node, it will return the key of the value.

Download Source Code:

 

Ads

Ads