Home > Enterprise >  Java: ddd elements from a list to another with conversion
Java: ddd elements from a list to another with conversion

Time:05-13

I am sure there are some functions to shorten my code below with some "lamda, map, Collections"-magic that does not need the loop to read from lsta and insert into lstb.

List <Integer> lsta = new ArrayList <Integer> ();
// ... insert into lsta

List <String> lstb = new ArrayList <String> ();
for (Integer a : lsta)
{
   lstb.add (foo (a));
}

CodePudding user response:

For Java 8 (result list is mutable, i.e can be changed, sorted, ..)

List<String> lstb = lsta.stream().map(a -> foo(a)).collect(Collectors.toList());

For Java 16 (result list is immutable, i.e cannot be added to or sorted ..)

List<String> lstb = lsta.stream().map(a -> foo(a)).toList();
  • Related