Issue
I am new to Java streams but need to master by practice really!
The collection input is made up of strings e.g. [name][dot][country]
, example as follows:
JAMES.BRITAIN
JOHN.BRITAIN
LEE.BRITAIN
GEORGE.FRANCE
LEON.FRANCE
MARSELLE.FRANCE
KOFI.GHANA
CHARLIE.GHANA
Please, how do I return a list of unique countries in a single stream statement?
Expected result will be a distinct list as follows:
BRITAIN
FRANCE
GHANA
In the real code the streams statement below gives me the list to be filtered i.e.:
List<String> allSolrCollections = (List<String>) findAllCollections()
.getJsonArray(SOLR_CLOUD_COLLECTION)
.getList()
.stream()
.map(object -> Objects.toString(object, null))
.collect(Collectors.toList());
Solution
Alternative solution
You can use the advantage of the method Pattern#splitAsStream(CharSerquence)
. Once you split each line into a new Stream, skip the first item, flatMap
the result into a new Stream and produce a Set
.
final Pattern pattern = Pattern.compile("\\.");
final Set<String> result = list.stream()
.flatMap(string -> pattern.splitAsStream(string).skip(1))
.collect(Collectors.toSet());
[GHANA, FRANCE, BRITAIN]
Answered By - Nikolas Charalambidis
Answer Checked By - David Goodson (JavaFixing Volunteer)