Reputation: 89
If we are working on collection....for example ArrayList then if ArrayList contains two types of objects(Integer and String) and we want to print them separately like integer objects in one group and string objects in another group. Please anyone tell me how can we do this?
Upvotes: 1
Views: 185
Reputation: 11126
May be below program can help you , it will dynamically create separate list of a type depending upon the object in your main list.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class SeparateType {
public static void main(String[] args) {
ArrayList<Object> arrayList=new ArrayList<>();
arrayList.add(101);
arrayList.add("Hello");
arrayList.add(102);
arrayList.add("World");
arrayList.add(103);
arrayList.add("String3");
arrayList.add(104);
arrayList.add("String4");
arrayList.add(1.0);
for (Map.Entry<Class,ArrayList<Object>> entry : convertToSeprateType(arrayList).entrySet()) {
System.out.println(entry.getKey().getSimpleName()+ " List values : " + entry.getValue());
}
}
public static <T> HashMap<Class,ArrayList<Object>> convertToSeprateType(ArrayList<Object> arrayList) {
HashMap<Class,ArrayList<Object>> hashMap=new HashMap<>();
final T val;
for(Object object:arrayList) {
if(hashMap.containsKey(object.getClass())) {
hashMap.get(object.getClass()).add(object);
}else {
ArrayList<T> list=new ArrayList<T>();
list.add((T) object);
hashMap.put(object.getClass(), (ArrayList<Object>) list);
}
}
return hashMap;
}
}
Output:
Integer List values : [101, 102, 103, 104]
Double List values : [1.0]
String List values : [Hello, World, String3, String4]
Upvotes: 0
Reputation: 2751
You can use List<Object>
but in that case you need to be careful. Have to check which instance it is and cast it accordingly.
See below example:
EDIT
added list for each group
List<Object> list = new ArrayList<>();
list.add("a");
list.add(2);
List<String> strList = new ArrayList<>();
List<Integer> intList = new ArrayList<>();
for (Object o : list) {
if (o instanceof String) {
System.out.println("String is: " + o);
strList.add((String) o);
}
if (o instanceof Integer) {
System.out.println("Integer is: " + o);
intList.add((Integer) o);
}
}
OP:
String is: a
Integer is: 2
Upvotes: 1