Home > Software design >  Populate a List of Double with String
Populate a List of Double with String

Time:01-22

I have a method which tests if a List of Double contains some String elements. This list is populated with Spring. I do not know how I can populate it with String in a JUnit.

My method converts String to Double with the following code:

// [...]
Obect element = list.get(i); // list is my List<Double>
if(element.getClass() == String.class) {
   list.set(i, Double.parseDouble((String) element));
}

CodePudding user response:

If you have a List<Double> as you claim, then it is impossible to add a String to it, so it does not make sense to test it. Nevertheless, requirements are not always making a lot of sense. So, your code is almost correct, but there is a mistake to fix inside (as you have already known when you have written the question). Let's see a better code:

Obect element = list.get(i); // list is my List<Double>
if(element.getClass().equals(String.class)) {
   list.set(i, Double.parseDouble((String) element));
}

You need to use the equals method instead of the == operator, because the == operator checks whether the operands are the same, yet, the getClass method creates a new instance of the Class class, which, by definition will not be the same as String.class. The equals method checks whether the two objects are similar. They are similar if the object is a String.

CodePudding user response:

It sounds like this is what you want. This conditional converts the strings to Double objects or passes on the doubles. It uses Double.valueOf() to avoid having to rebox the double.

I also prefer to simply create a new list. Inserting values as you are doing can cause quite a bit of copying (or counting if a linkedList). Also using instanceof as suggested in the comments.

List<Object> list = Arrays.asList(
        2.3, 4.7, null,  "99.3", "47.2", null, 2.8, "48.7");
    

List<Object> result =
        list.stream().map(ob -> (ob instanceof String) ?
                Double.valueOf((String)ob) : ob).toList();

System.out.println(result);

Prints

[2.3, 4.7, null, 99.3, 47.2, null, 2.8, 48.7]

If you want just a list of Doubles then you would need to cast the last item in the ternary (?:) construct to double (e.g. (Double)ob). Filtering out any nulls may also be desirable.

  •  Tags:  
  • Related