Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening a collection within collection to get a single List<>

I'm quite new to using Java and was trying to flatten collections within collections using map to try and get a single List. However I don't seem to be able to get this working. In order to reproduce this I've created quite a simple example of what I'm trying to do. Here is what I have so far:

ClassA

import java.util.List;

public class ClassA {
    private List<ClassB> listOfClassB;

    public ClassA(List<ClassB> listOfClassB) {
        this.listOfClassB = listOfClassB;
    }

    public List<ClassB> getListOfClassB() {
        return this.listOfClassB;
    }
}

ClassB

    public class ClassB {
    private String item;

    public ClassB(String item) {
        this.item = item;
    }

    public String getItem() {
        return item;
    }
}

Main

public class Main {
    public static void main(String[] args) {
        ClassB firstClass = new ClassB("A");
        ClassB secondClass = new ClassB("B");
        ClassB thirdClass = new ClassB("C");
        ClassB fourthClass = new ClassB("D");
        ArrayList<ClassB> firstClassList = new ArrayList<>();
        ArrayList<ClassB> secondClassList = new ArrayList<>();

        firstClassList.add(firstClass);
        firstClassList.add(secondClass);
        secondClassList.add(thirdClass);
        secondClassList.add(fourthClass);

        ArrayList<ClassA> classes = new ArrayList<>();
        classes.add(new ClassA(firstClassList));
        classes.add(new ClassA(secondClassList));

        List<List<String>> collect = classes.stream().map(c -> c.getListOfClassB().stream().map(ClassB::getItem).collect(Collectors.toList())).collect(Collectors.toList());
    }
}

As you can see on the bottom I am able to get List<List<String>> but what I'm looking to get is a List<String> of the items within ClassB. I've tried using a flatmap for this but I couldn't get it working and was looking for some guidance.

Thanks in advance.

like image 821
Serberuss Avatar asked Dec 18 '22 20:12

Serberuss


1 Answers

Here is the flatmap example which works fine:

classes.stream().flatMap(aclass -> aclass.getListOfClassB().stream())
    .forEach(b -> System.out.println("Class B Item Name : "+b.getItem()));

It gives the following output:

Class B Item Name : A
Class B Item Name : B
Class B Item Name : C
Class B Item Name : D

and to get the exact answer:

List<String> collect2 = classes.stream().flatMap(aclass -> aclass.getListOfClassB().stream())
    .map(b -> b.getItem())
    .collect(Collectors.toList());

it gives me a list as follows:

collect2 : [A, B, C, D]
like image 105
KayV Avatar answered Apr 27 '23 23:04

KayV