简体   繁体   中英

Java Lists list item values

I have a List for example and I want to call a function on them and list returned answers

final List<String> sources = new ArrayList<>();
// initialize
final List<Integer> answers = new ArrayList<>();
for(final String source : sources)
    answers.add(calculate(source));

Is there any standard function in GoogleGuava or ApacheCommons to use it instead of these messy codes

Like (example purpose):

final List<String> answers = Lists.calculate(sources, new CalculateListener(..));

And for easy understanding: UnderscoreJs in JavaScript has a method map I want something like that in java GoogleGuava or ApacheCommons if exists

You can play a bit with the Function interface and the Iterables class.

From what I can see from your example, you're trying to transform a source to calculated source , so the code would look like:

Function<String, String> transformer = new Function<String, String>() {
    public String apply(String source) {
        return calculate(source);
    }
};
Iterable<String> calculatedSources = Iterables.transform(sources, transformer);
List<String> calculatedSourcesAsAList = Lists.newArrayList(calculatedSources);

As a side note, this often seen type of operation is very well covered in the Java8's Stream features, where you would have to just map the sources to the calculated ones and then collect the result. And it's just a one-liner:

sources.stream().map(source -> calculate(source)).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