On this quick Byte – we’ll check out how one can accumulate and switch a listing right into a singleton set in Java, utilizing the Useful API, and paired with the collectingAndThen()
collector.
Recommendation: If you would like to learn extra about collectingAndThen()
– learn our in-depth “Information to Java 8 Collectors: collectingAndThen()”!
Flip a Stream right into a Singleton Set
When amassing a stream again into a listing (streamed from a Java Assortment
) – chances are you’ll determine to determine to return an immutable singleton Set
that incorporates a single (and strictly single) immutable ingredient.
An intuitive technique to utilize right here is collectingAndThen()
which lets you accumulate()
a Stream
after which run an nameless perform on the consequence:
public class Singleton {
personal remaining Stream<?> stream;
public Set<?> getSingleton() {
return stream.accumulate(
collectingAndThen(
toList(),
l -> {
if (l.dimension() > 1){
throw new RuntimeException();
} else{
return l.isEmpty()
? emptySet()
: singleton(l.get(0));
}
}
)
);
}
}
Right here, we have collected the stream right into a Record
, which is a terminal operation (ending the stream). Then, that checklist is streamed once more, checking for the dimensions. If the dimensions is bigger than 1 – a singleton Set
can’t be created. On this instance, we anticipate that the operation pipeline earlier than the collectingAndThen()
name, the stream is filtered of all parts however one.
After the dimensions verify – we will create a brand new singleton Set
with singleton(l.get(0))
– passing the primary (and solely) ingredient of the checklist into the Collections.singleton()
technique.
You possibly can take a look at the strategy and assert the right output with:
@Take a look at
public void shouldCreateSingleton() {
Singleton s1 = new Singleton(Stream.of(1,2));
assertThrows(
RuntimeException.class,
() -> s1.getSingleton()
);
Singleton s2 = new Singleton(Stream.empty());
Set<?> singleton = s2.getSingleton();
assertEquals("[]", singleton.toString());
Singleton s3 = new Singleton(Stream.of(1));
singleton = s3.getSingleton();
assertEquals("[1]", singleton.toString());
}
Conclusion
On this quick Byte – we took a take a look at how one can accumulate and switch a listing right into a singleton set in Java 8+.