i have multiple data type like eg. {10, 12.5, 20, 50, "abcd", xyz} So, i want to pass these data type through ArrayList and then filter only the integer value.
If this can be done then can any of you please provide a sample code to demonstrate it. If no, then what's the reason.
Thanks in advance
So, i assume that this can be done by creating an object of arraylist. ArrayList<Object> list = new ArrayList <>(); And then can add all these values using list.add();
But then in this how can we filter integer after adding the values is where i got stuck
CodePudding user response:
Well, you must indeed create a list which accepts both String
s and Integer
s. The only way is to indeed create a List<Object>
.
In order to retrieve the integer values, you could just test whether the contained object is of a certain type:
for (var element : list) {
if (element instanceof Integer) {
// Do something with the value
}
}
Or using streams:
list.stream()
.filter(element -> element instanceof Integer)
// or .filter(Integer.class::isInstance)
.forEach(element -> {
// Do something with the value
});
CodePudding user response:
First part of your problem is right, just create an ArrayList<Object>
Then, try this:
ArrayList<Integer> intList = new ArrayList<Integer>();
for(Object o : list){
try{
intList.add(Integer.parseInt(o.toString()))
}catch(NumberFormatException e) {
//optional code
}
}
CodePudding user response:
List<Object> list= new ArrayList<>();
list.add(1);// interger
list.add(11.00);// Double
list.add("Strings");//String
System.out.println(list);