使用流将一个列表转换为另一个列表

t5zmwmid  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(416)

鉴于,

class Foo {
private Long id;
private String name;
private String category;
private List<String> categories;
// getters & setters
}

我有一个物品清单。

final Foo f1 = new Foo(1L, "a", "c1");
final Foo f2 = new Foo(1L, "a", "c2");
final Foo f3 = new Foo(2L, "a", "c1");

final List<Foo> li = List.of(f1, f2, f3);

看起来像

{[Foo [id=1, name=a, category=c1, categories=null], Foo [id=1, name=a, category=c2, categories=null]], [Foo [id=2, name=a, category=c1, categories=null]]}

我想把它变成

[Foo [id=1, name=a, category=null, categories=[c1, c2]], Foo [id=2, name=a, category=null, categories=[c1]]]

i、 e.核对个人资料 category 进入一个列表 categories .
这是实现我想要的当前代码。

public static void main(final String[] args) {
        final Foo f1 = new Foo(1L, "a", "c1");
        final Foo f2 = new Foo(1L, "a", "c2");
        final Foo f3 = new Foo(2L, "a", "c1");

        final List<Foo> li = List.of(f1, f2, f3);
        li.forEach(e -> System.out.println(e));

        final Map<Long, List<Foo>> collect = li.stream().collect(Collectors.groupingBy(Foo::getId));
        System.out.println(collect);

        final List<Foo> grouped = new ArrayList<>();
        collect.forEach((k, v) -> {
            System.out
                    .println("key=" + k + "val=" + v.stream().map(e1 -> e1.getCategory()).collect(Collectors.toList()));

            final Foo foo = collect.get(k).get(0);
            foo.setCategories(v.stream().map(e1 -> e1.getCategory()).collect(Collectors.toList()));
            foo.setCategory(null);

            grouped.add(foo);
        });

        System.out.println(grouped);
    }

有没有任何方法可以单独使用streams和lambda而不必分成多个步骤来实现这一点?目标是使这段代码更加优雅、可读,并向读者传达意图。
这个问题在本质上类似于groupby和sum对象,比如在带有javalambdas的sql中?但是没有帮助我,因为这里做了聚合,而这里不是聚合。

xdnvmnnf

xdnvmnnf1#

可以通过实现 merge 函数,该函数将累积类别列表中的类别,然后使用 reduce 流的操作:

class Foo {
    static Foo merge(Foo accum, Foo other) {
        if (null == accum.categories) {
            accum.categories = new ArrayList<>();
            if (null != accum.category) {
                accum.categories.add(accum.category);
                accum.category = null;
            }
        }
        accum.categories.add(other.category);

        return accum;
    }
}

实施:

static List<Foo> joinedCategoriesReduce(List<Foo> input) {
    return input
            .stream()
            .collect(Collectors.groupingBy(Foo::getId))  // Map<Integer, List<Foo>>
            .values().stream()   // Stream<List<Foo>>
            .map(v -> v.stream() // Stream<Foo>
                    .reduce(new Foo(v.get(0).getId(), v.get(0).getName(), (String)null), Foo::merge)
            )
            .collect(Collectors.toList());
}

测试

final Foo f1 = new Foo(1L, "a", "c1");
final Foo f2 = new Foo(1L, "a", "c2");
final Foo f3 = new Foo(2L, "a", "c1");

final List<Foo> li = List.of(f1, f2, f3);
joinedCategoriesReduce(li).forEach(System.out::println);

输出

Foo(id=1, name=a, category=null, categories=[c1, c2])
Foo(id=2, name=a, category=null, categories=[c1])

另一个选项是提供接受类别列表的foo构造函数:

// class Foo
public Foo(Long id, String name, List<String> cats) {
    this.id = id;
    this.name = name;
    this.categories = cats;
}

然后Map条目可以很容易地重新Map到 Foo 包含类别列表的示例:

static List<Foo> joinedCategoriesMap(List<Foo> input) {
    return input
            .stream()
            .collect(Collectors.groupingBy(Foo::getId))
            .values().stream()
            .map(v -> new Foo(
                    v.get(0).getId(),
                    v.get(0).getName(),
                    v.stream().map(Foo::getCategory).collect(Collectors.toList()))
            )
            .collect(Collectors.toList());
}

在线演示

相关问题