Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing Integers operation on List<Objects>

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>

  1. Strings may be appended based on their length.
  2. Floating numbers needs to be rounded

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.

like image 801
Devendra Lattu Avatar asked Jul 02 '26 10:07

Devendra Lattu


1 Answers

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.

like image 120
developer Avatar answered Jul 04 '26 23:07

developer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!