简体   繁体   中英

Java: add elements from a list to another with conversion

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));
}

For Java 8+ (result list is mutable, ie can be changed, sorted, ..)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM