Reputation: 329
I want to retrieve single String from hashtable.
Here, In my code the Hashtable key is returning some id [ex 1234] and value is returning some url [ex ww.abc.com/] and at the last step I am appending this id to the url.
I want my function to return that complete url [Appended one ], as with each iteration of that hashtable the key and value would be different. so that url would also be different. I want this function to retrieve URL (Key-Value pair) with each table iteration.
public String readFromHashtable(Hashtable<String, String> recruiter){
String url=null;
try{
Iterator<Map.Entry<String, String>> it = recruiter.entrySet().iterator();
while (it.hasNext())
{
Map.Entry<String, String> pair = it.next();
String key = pair.getKey();
String value = pair.getValue();
url =new StringBuffer(value).append(key).toString();
System.out.println(url);
}
}catch(Exception e){
e.printStackTrace();
}
return url;
}
Upvotes: 0
Views: 107
Reputation: 1502006
It's not really clear what you're trying to achieve, but I suspect you want to return an Iterable<String>
from your method rather than a single string. For example:
// No need to tie ourselves to Hashtable...
public static Iterable<String> readFromMap(final Map<String, String> map) {
return new Iterable<String>() {
@Override public Iterator<String> iterator() {
return new Iterator<String>() {
private final Iterator<Map.Entry<String, String>> iterator
= map.entrySet().iterator();
@Override public void remove() {
iterator.remove();
}
@Override public boolean hasNext() {
return iterator.hasNext();
}
@Override public String next() {
Map.Entry<String, String> entry = iterator.next();
return entry.getValue() + entry.getKey();
}
};
}
};
}
This looks like a lot of code, but really it's just wrapping the iterator returned by Map.entrySet().iterator()
so that it can transform each entry. Another option would be to use Iterables
in Guava. Something like:
// No need to tie ourselves to Hashtable...
public static Iterable<String> readFromMap(final Map<String, String> map) {
return Iterables.transform(map.entrySet(),
new Function<Map.Entry<String, String>, String>() {
@Override public String apply(Map.Entry<String, String> entry) {
return entry.getValue() + entry.getKey();
}
});
}
Upvotes: 1