I'm trying to achieve this using only functional programming constructs (Streams, Collectors, lambda expressions).
Let's say list
is a String[]
:
{"Apple", "Samsung", "LG", "Oppo", "Apple", "Huawei", "Oppo"}
I want to print out a distinct list of brand names from this array, and number them, i.e.:
1. Apple
2. Huawei
3. LG
4. Oppo
5. Samsung
I can print out the unique elements (sorted):
Stream.of(list)
.distinct()
.sorted()
.forEach(System.out::println);
But this does not show the preceding counter. I tried Collectors.counting()
but that, of course, didn't work.
Any help from FP experts?
Edit: I understand some other questions have asked about iterating over a stream with indices. However, I can't simply do:
IntStream.range(0, list.length)
.mapToObj(a -> (a+1) + ". " + list[a])
.collect(Collectors.toList())
.forEach(System.out::println);
because the original array contains duplicate elements. There might also be other map
and filter
operations I may need to perform on the stream before I print the result.