Home Java Example Java Util Determining If a Preference Node Contains a Specific Value

Related Tutorials


 
 

Share on Google+Share on Google+

Determining If a Preference Node Contains a Specific Value

Advertisement
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:

 

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 17, 2009

Related Tutorials

Discuss: Determining If a Preference Node Contains a Specific Value  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com