简体   繁体   中英

Multiple loops with the same logic just different fields

I have multiple loops using the same logic. The only change is the field!

MyObjectList.stream()
        .map(MyObject::getValue1)
        .map(String::valueOf)
        .collect(Collectors.joining(", "));

I have the same logic for getValue2, getValue3, and so on.

How can I make it generic? Like having one method/class that will deal with all these cases?

You can try this

public <T, R> String join(Collection<T> collection, Function<T, R> mapper) {
    return collection.stream()
               .map(mapper)
               .map(String::valueOf)
               .collect(Collectors.joining(", "));
}

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