使用自定义列表供应商收集列表?

发布于 2025-02-06 06:18:10 字数 1490 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

街道布景 2025-02-13 06:18:10

如果您的目的是将一种类型的列表转换为另一种类型,则需要添加流式处理,collector.tocollection并修复某些通用类型,以便“列表”和“ clazz”与通用匹配参数:

protected static <T, R, P extends List<R>>
void mapper(Function<? super T, ? extends R> mapper, List<T> list, P clazz){
    final Supplier<P> p = () -> clazz;
    list.stream().map(mapper).collect(Collectors.toCollection(p));
}

例如,以下将字符串列表转换为其各自长度的另一个列表:

List<String> input = List.of("abc","defg");
ArrayList<Integer> output = new ArrayList<>();

mapper(s -> Integer.valueOf(s.length()), input, output);
// =>> output is [3, 4]

If your intention is to convert a list of one type to another, you need to add stream handling, Collectors.toCollection and fix some of the generic types so that "list" and "clazz" match the generic parameters:

protected static <T, R, P extends List<R>>
void mapper(Function<? super T, ? extends R> mapper, List<T> list, P clazz){
    final Supplier<P> p = () -> clazz;
    list.stream().map(mapper).collect(Collectors.toCollection(p));
}

For example, the following converts a list of strings into another list of their respective lengths:

List<String> input = List.of("abc","defg");
ArrayList<Integer> output = new ArrayList<>();

mapper(s -> Integer.valueOf(s.length()), input, output);
// =>> output is [3, 4]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文