简体   繁体   中英

Mapping over a list in Java

In Java 8 I can map over streams with the map method, eg

Stream.of("Hello", "world").map(s -> s.length())

gives me a stream containing the integers [5, 5] . I am trying to do the same with lists. I have come up with

List<String> list = ...

list.stream().map(s -> s.length()).collect(Collectors.toList())

This works but is rather verbose. Is there a more concise solution? Ideally, there would be a similar map method for lists, but I haven't found any. So, are there any alternatives?

As compact as possible

Just wrap it into your own utility function:

public <T, S> List<S> mapBy(List<T> items, Function<T, S> mapFn) {
    return items.stream().map(mapFn).collect(Collectors.toList());
}

Now you can just use mapBy(students, Student::getName) . It doesn't get less verbose than that.

Note that this is only useful if that's the only data mutation you want to make. Once you have more stream operators you want to apply it'd be better to do just that as otherwise you keep creating intermediate lists, which is quite wasteful.

Think practically to do operation on each element in list you need to either stream it or loop it, so stream is more concise than loop. for more info you can replace lambda expression with method reference operator

list.stream().map(String::length).collect(Collectors.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