简体   繁体   中英

How to convert 2 dimensional array to Set?

for the example I have Foo Object then I've some Foo Data inside 2-d Array Foo[][] . I want to convert it into Set<Foo> in order to just get Set of Foo unique data. How can I do that?

A simple (but not the best performing) solution would be to use java streams:

Set<Foo> set = Arrays.stream(array)
    .flatMap(Arrays::stream)
    .collect(Collectors.toSet());

The above code snippet first creates a Stream<Foo[]> with the Arrays.stream(array) statement.

Then it flattens that stream into Stream<Foo> with the second statement: .flatMap(Arrays::stream) which behaves the same as .flatMap(arr -> Arrays.stream(arr)) .

At last it creates a Set<Foo> out of the flattened stream with .collect(Collectors.toSet()) .

I suggest having a deep look at the Java Streaming API, introduced with Java 8. It can do much more than just mapping a 2d array into a Set.


Another approach is just to use 2 nested for loops:

Set<Foo> set = new HashSet<>(); // or LinkedHashSet if you need a similar order than the array
for(Foo[] inner : array) {
    for(Foo item : inner) {
        set.add(item);
    }
}
public <T> List<T> twoDArrayToList(T[][] twoDArray) {
    List<T> list = new ArrayList<T>();
    for (T[] array : twoDArray) {
        list.addAll(Arrays.asList(array));
    }
    return list;
}

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