Doerad
Doerad

Reputation: 79

Java lambda expression for counting unique objects

I have set up this stream below and cant use the method count() on .map. Only on filter. But I havent set up any filter condition. How could I do it on an array of Strings for this stream below?

I want to sort out strings given the regex in replaceAll and get the unique strings and get the number of unique strings total.

Stream newStream = Arrays.stream(arr)
                    .map(s -> s.replaceAll("[^a-z]", ""))
                    .distinct()

Upvotes: 2

Views: 3898

Answers (3)

KrishPrabakar
KrishPrabakar

Reputation: 2842

Both collecting as a list and getting the total count are terminal operations, hence you can do only either on a live stream.

If you must use the same stream to get both the list of strings and count, one (hacky) option would be to use Supplier<Stream<T>>:

String text = "FOO bar BAZ TEXT text some";
String[] arr = text.split(" ");

Supplier<Stream<String>> sameStream = () -> Arrays.stream(arr)
        .map(s -> s.replaceAll("[^a-z]", ""))
        .distinct()
        .filter(s -> !s.isEmpty())
        .sorted();

System.out.println("Unique strings are: " + sameStream.get().collect(Collectors.toList()));
System.out.println("Count of Unique strings are: " + sameStream.get().count());

Above yields this output:

Unique strings are: [bar, some, text]
Count of Unique strings are: 3

Upvotes: 0

fps
fps

Reputation: 34450

I'm not sure I completely understand your requirement. It seems you want a List with the distinct strings sorted after applying the regex to each element of the array. This List would have both the elements and their count:

List<String> list = Arrays.stream(arr)
    .map(s -> s.replaceAll("[^a-z]", ""))
    .distinct()
    .sorted()
    .collect(Collectors.toList());

Now, list holds the elements. And if you want to also know how many elements it contains, simply use the List.size method:

int count = list.size();

EDIT: If you also need a Stream with the strings changed, unique and sorted, simply create a new Stream from list:

Stream<String> newStream = list.stream();

Upvotes: 2

Naman
Naman

Reputation: 31858

If you were to count the number of distinct strings, you can do it like :

long countDistinct = Arrays.stream(arr)
        .map(s -> s.replaceAll("[^a-z]", ""))
        .distinct() // intermediate operation with unique strings as 'Stream' return type
        .count();   // terminal operation with count of such strings as return type

Upvotes: 4

Related Questions