I have a List of Objects which I want to convert to a List of Integers
List<Object> list = new ArrayList<>();
list.add("StringTest");
list.add(10);
list.add(5.9);
list.add(2.5f);
list.add(12L);
... // different datatypes
List<Integer> result = new ArrayList<>();
// convert items from list and add to result
What could be a good custom implementation to add values from different datatypes of List<Object> to a List<Integer>
I know standard implmentation on How to cast an Object to an int in java? but I am looking for a good structure to write a generic one.
You can use streams to process the list of Object types as shown in the below code (follow the comments):
//Collect all Number types to ints
List<Integer> output1 = list.stream().
filter(val -> !(val instanceof String)).//filter non-String types
map(val -> ((Number)val).floatValue()).//convert to Number & get float value
map(val -> (int)Math.round(val)).//apply Math.round
collect(Collectors.toList());//collect as List
//Collect all String types to int
List<Integer> output2 = list.stream().
filter(val -> (val instanceof String)).//filter String types
map(val -> (((String)val).length())).//get String lengths
collect(Collectors.toList());//collect as List
//Now, merge both the lists
output2.addAll(output1);
Floating numbers needs to be rounded
You need to first convert the Number value to float using floatValue() method and then apply Math.round as shown above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With