Saturday, February 14, 2009

Java Issues and Solutions - 1

How to convert an array to list?
Solution:
This is an example to convert String of arrays to list of arrays.//Say array is initialized as below
String[] s = new String[3];
s[0] = "test1";
s[1] = "test2";
s[2] = "test3";
//Method to convert array to list
private List convetArrayToList(String[] s)
{
List testList = new ArrayList();

//Conversion from array to list
int size = s.length;
for(int i=0;i<size;i++)
{
testList.add(s[i]);
}
return testList;
}

How to convert a list to array?
Solution:

This is an example to convert array list to String of arrays.
//Say list is initialized as below
List testList = new ArrayList();testList.add("test1");
testList.add("test2");
testList.add("test3");
//Method to convert list to array
private String[] convetListToArray(List list)
{
String[] s = new String[list.size()];
Iterator listIterator = list.iterator();
int i = 0;
while(listIterator.hasNext())
{
Object temp = listIterator.hasNext();
if(temp instanceof String)
s[i++] = (String) temp;
}
return s;
}

How to convert a numeric string to integer or double etc.,?
Solution:
Use the parseXXX method of that data types wrapper class.
String intString = "123";
int value = Integer.parseInt(intString);
String doubleString = "123.45";
double value = Double.parseDouble(doubleString);

How to store the elements in sorted order?
Solution:
Use tree set to store the elements, it stores the elements in sorted order.
Set s = new TreeSet();
s.add("CCC");
s.add("AAA");
s.add("GGG");
s.add("BBB");
Iterator setIterator = s.iterator();
while(setIterator.hasNext())
{
Object temp = setIterator.next();
String value = (String)temp;
System.out.println(value);
}
This will return the elements in the below order.
AAA
BBB
CCC
GGG

How get all the elements of a map without knowing the keys? or How to iterate through a map elements ?
We can't directly iterate through the map, you can do it by getting all the keys of the map into a set, iterating that set and by passing the set element to map as key you can get the corresponding value from map.
Map m = new Map();
m.put("1", "First");
m.put("2", "Second");
m.put("3", "Third");
m.put("4", "Fourth");
//Get all the keys from map
Set s = m.keySet();
Iterator setIterator = s.iterator();
while(setIterator.hasNext())
{
String key = (String) setIterator.next();
//Pass each key to the map to get the map value
//to the corresponding key
String value = (String)m.get(key);
System.out.println("The key is: "+key+" :value is: "+value);
}
This will give the output:
The key is: 1 :value is: First
The key is: 2 :value is: Second
The key is: 3 :value is: Third
The key is: 4 :value is: Fourth

No comments:

Post a Comment