0

I am making a program that converts pictures to a grayscale form and from that grayscale form it converts it to a fairey format.

I am using nested for-loops to convert a nested list. This works perfectly but I want to do it using streams and if I do it using that the output changes, but I think it should result in the same output. Where am I wrong?

grayPhoto is a List<List<Graypixel>>

Do any of you see what I'm doing wrong or how the stream should be?

for (int i = 0; i < grayPhoto.size(); i++) {
    for (int j = 0; j < grayPhoto.get(i).size(); j++) {
        numbersSet.add(grayPhoto.get(i).get(j));
    }
}

grayPhoto.forEach(r -> r.forEach(e -> numbersSet.add(e)));
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Mathias Gielen
  • 91
  • 1
  • 1
  • 4
  • 2
    The idiomatic way would be to use flatMap and to collect to a Set, using Collectors.toSet(). https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#flatMap-java.util.function.Function- Are you asking about an error? – JB Nizet Dec 07 '19 at 14:46
  • and what is `numbersSet`? ( I mean why is there such a difference in the name for the same data type.) Apart from which, is it a `List` or a `Set`? – Naman Dec 07 '19 at 14:49
  • You may now think about accepting an answer ;) to reward those who spent time for you ;) Or comment an answer to get details – azro Dec 21 '19 at 22:28

2 Answers2

3

You need to use flatMap operation, to flatten your list of list to a list (a stream of list to a stream here) then collect as a Set :

Set<Graypixel> numbersSet = grayPhoto.stream()
                                     .flatMap(List::stream)
                                     .collect(Collectors.toSet());
azro
  • 53,056
  • 7
  • 34
  • 70
2

I think it should result in the same output. Where am I wrong?

You aren’t wrong. Both your ways of converting do result in the same set. I am assuming that numbersSet is a Set<Graypixel>, for example a HashSet.

Even if it was a List<Graypixel>, the result would also be the same list in both cases. Of course, if you run both snippets, all the pixels will be added twice to the list.

For the canonical way of converting see the comment by JB Nizet or the answer by azro.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161