Arrays.asList not flattening in Java, what should I use instead?

340 Views Asked by At

Hi I need to convert a SortedSet> to an array of integers but not sure how to do it.

This is the SortedSet I want to convert:

private SortedSet<List<Integer>> coords;

and this is the get method I am using which shows as an error:

public List<Integer> getCoords() {
    return Arrays.asList(coords);
}

If I want to do something like this, would I have to go through the entire SortedList and make a new int[] array and just put all the values inside it? Or is there a much nicer way? I thought Arrays.asList could do this but now I am confused!

Thanks for reading!

3

There are 3 best solutions below

7
On BEST ANSWER

Arrays.asList() will not flatten anything!

What you want is this:

public List<Integer> getCoords()
{
    final List<Integer> ret = new ArrayList<>();
    for (final List<Integer> l: coords)
        ret.addAll(l);
    return ret;
}

With Java 8, one example would be:

public List<Integer> getCoords()
{
    final List<Integer> ret = new ArrayList<>();
    coords.stream().forEach(ret::addAll);
    return ret;
}

There are other, shorter examples (see other answers or comments to this answer) as well.

0
On

You want to make an array of all the integers inside all the lists in your sorted set?

You'll have to iterate through the set, and concatenate the results of each list.toArray();

https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#toArray(T[])

2
On

@fge gives you the solution. However if you are using you could use the brand new stream API and call flatMap (which is the operation you are looking for).

public List<Integer> getCoords() {
        return coords.stream()
                     .flatMap(list -> list.stream()) //or .flatMap(List::stream)
                     .collect(Collectors.toList());
}