简体   繁体   中英

How to convert nested ArrayList in Array?

I have to convert an ArrayList of ArrayList in to Array.

List<List<TockaXY>> clustersPorazdeljeni = new ArrayList<>(centers.size());

I know that is possible to convert a single ArrayList to Array like

 TockaXY[] arrayOfClusters = clustersPorazdeljeni.toArray(new TockaXY[centers.size()]);

But these does not convert the nested part. As i understand is now array of ArrayLists. So is it possible to get an Array out of nested ArrayLists?

You can use flatMap:

List<List<TockaXY>> clustersPorazdeljeni = new ArrayList<>();
TockaXY[] flattened = clustersPorazdeljeni.stream()
        .flatMap(x -> x.stream())
        .toArray(x -> new TockaXY[0]);

It is possible using Java Stream and Stream::flatMap :

List<List<TockaXY>> clustersPorazdeljeni = new ArrayList<>();

TockaXY[] strings = clustersPorazdeljeni.stream()
    .flatMap(Collection::stream)
    .toArray(TockaXY[]::new);

There is linear alternative for flatMap():

    List<List<TockaXY>> clustersPorazdeljeni = new ArrayList<>();

    List<TockaXY> flatArray = new ArrayList<>();
    clustersPorazdeljeni.forEach(flatArray::addAll);
    TockaXY[] arrayOfClusters = flatArray.toArray(new TockaXY[0]);

Or with flatMap:

TockaXY[] arrayOfClusters = clustersPorazdeljeni.stream().flatMap(Collection::stream).toArray(TockaXY[]::new);
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(4);
list.add(5);
Object[] array = list.toArray();

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