Question

I am working on a Java app and I have two different strongly typed arrays. I need one, a List<Float> turned into a List<Integer>. Alas i cannot use the primitive types, I am stuck with Float and Integer and not float and integer.

What is the best way to convert one from the other?

EDIT I have only been using java for a week or so for some work related projects, so there is a lot that in the language that I have yet to find. When trying to cast something like:

Long projectId = Long.parseLong(myFloat.toString()); 

I was getting java.lang.NumberFormatExceptions, and these were driving me up the wall. Especially as there is little help from google when trying to search Long and long.

Était-ce utile?

La solution 2

In my opinion (which is an opinion) the best way would be the way that is the simplest.

That is a biased opinion based on the following assumptions:

  1. You haven't profiled your code, so it's probably an unknown if this section of code is a performance bottleneck. This means that optimizing it is premature optimization.
  2. If you do it the simplest way, then you will likely incur the fewest bugs due to "cleverness".

An example follows

 List<Float> floats = ...;
 List<Integer> integers = new ArrayList<Integer>();
 for (Float item : floats) {
    integers.add(item.intValue());
 } 
 return integers;

And as many have noted, since you didn't specify what was important, it is hard to know which solution might best satisfy your unspoken requirements.

Autres conseils

Using Java 8:

List<Float> list = Arrays.asList(1.0f, 2.0f, 3.0f);
List<Integer> intList = list.stream().map(Float::intValue).collect(Collectors.toList());

Depends on what you consider as "best" way: run faster? shorter code? less object created?

Having a for loop and do the conversion will probably run fastest. Just a hint that if you are using ArrayList, consider pre-allocate the size you need. That save you some time of array resizing.

if you are looking for shorter code, if you are using Java8, I believe you can use something like (not tested)

List<Long> result = doubleList.stream().map(d->(Long)(double)d).collect(Collector.toList());

I believe there are similar thing you can do in pre-Java8 with help of Guava, of course code will be a bit longer.

If you want least object to be created, and if you know you are going to access only a few objects in the list, you may consider writing a wrapper, which bears the interface of List<Long>, and for most of the method call, delegate to an internal List<Double>.

I don't think there is any "best way". If you need accuracy, consider using String and BigDecimal, and then converting BigDecimal to int, double, float, or whatever other numeric type is appropriate.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top