Java ArrayList <T> .convertall

Is there something like C # .convertall in Java?

how

ArrayList<MyCalss> list = new ArrayList<MyClass>();
list.convertall(new Converter(...));

      

+3


source to share


2 answers


Depending on what exactly you mean by the converter, something like this might work in Java 8:

ArrayList<MyClass> list = new ArrayList<MyClass>(someObjectsToFillTheList);
List<OtherClass> list2 = list.stream()
    .map(s -> new OtherClass(s)).collect(Collectors.toList());

      



In this case, the conversion is done by the constructor OtherClass

.

+4


source


For Java 8 see jpmath's answer. For lower versions, you either have to take a long walk or write a loop that iterates through your collection and adds the transformed result to another list, or you can look at the Guava Library .



Since there are no lambdas / closures in Java <8, you can use the anonymous function in the Lists # transform () - method .

0


source







All Articles