1

I don't know how you guys call this but is it possible to write something like that? Only these two lines.

List<Celsius> listOfCelsiuses = new ArrayList<>(); List<Fahrenheit> listOfFahrenheits = new ArrayList<>(listOfCelsiuses); 

It basically takes a list of celsiuses and returns a list of fahrenheits. But where should I implement that conversion logic?

4
  • First off, the new implementation should look like, new ArrayList<Celsius>(); But, you can not do that for types that are not the same; you would have to create your own function that would take an ArrayList<Celsius> and return and ArrayList<Fahrenheit> Commented Feb 23, 2015 at 1:35
  • Do you have some method which can take instance of Celsius and return Fahrenheit? Commented Feb 23, 2015 at 1:42
  • Is Fahrenheit a parent class for the Celsius class? If so then you need two lines: List<Fahrenheit> listOfFahrenheits = new ArrayList<>(); listOfFahrenheits.addAll(listOfCelsiuses); Commented Feb 23, 2015 at 3:06
  • Fahrenheit is not a parent class for the Celsius class Commented Feb 24, 2015 at 11:50

1 Answer 1

6

In java 8 this is a candidate for Stream and a map call:

List<Celsius> celsius; final List<Fahrenheit> fahrenheit = celsius.stream() .map(c -> convert(c)) .collect(Collectors.toList()); private static Fahrenheit convert(Celsius c) { 

Prior to jre 8, you could use Gauva's Lists.transform with a Function that does the conversion.

Sign up to request clarification or add additional context in comments.

1 Comment

It seems that there is no built-in Java SE7 solution. Something like that just needs to override some built-in method. So I accept your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.