Project architect: @victornoel
Cactoos is a collection of object-oriented Java primitives.
We are not happy with JDK, Guava, and Apache Commons because they are procedural and not object-oriented. They do their job, but mostly through static methods. Cactoos is suggesting to do almost exactly the same, but through objects.
These are the design principles behind Cactoos.
The library has no dependencies. All you need is this:
Maven:
<dependency>
<groupId>org.cactoos</groupId>
<artifactId>cactoos</artifactId>
<version>0.57.0</version>
</dependency>Gradle:
dependencies {
compile 'org.cactoos:cactoos::0.57.0'
}Java version required: 17+.
StackOverflow tag is cactoos.
More about it here: Object-Oriented Declarative Input/Output in Cactoos.
To read a text file in UTF-8:
String text = new TextOf(
new File("/code/a.txt")
).asString();To write a text into a file:
new LengthOf(
new TeeInput(
"Hello, world!",
new File("/code/a.txt")
)
).value();To read a binary file from classpath:
byte[] data = new BytesOf(
new ResourceOf("foo/img.jpg")
).asBytes();To format a text:
String text = new FormattedText(
"How are you, %s?",
name
).asString();To manipulate text:
// To lower case
new Lowered(
new TextOf("Hello")
);
// To upper case
new Upper(
new TextOf("Hello")
);More about it here: Lazy Loading and Caching via Sticky Cactoos Primitives.
To filter a collection:
Collection<String> filtered = new ListOf<>(
new Filtered<>(
s -> s.length() > 4,
new IterableOf<>("hello", "world", "dude")
)
);To flatten one iterable:
new Joined<>(
new Mapped<IterableOf<>>(
iter -> new IterableOf<>(
new ListOf<>(iter).toArray(new Integer[]{})
),
new IterableOf<>(1, 2, 3, 4, 5, 6)
)
); // Iterable<Integer>To flatten and join several iterables:
new Joined<>(
new Mapped<IterableOf<>>(
iter -> new IterableOf<>(
new Joined<>(iter)
),
new Joined<>(
new IterableOf<>(new IterableOf<>(1, 2, 3)),
new IterableOf<>(new IterableOf<>(4, 5, 6))
)
)
); // Iterable<Integer>To iterate a collection:
new And(
new Mapped<>(
new FuncOf<>(
input -> {
System.out.printf("Item: %s\n", input);
},
new True()
),
new IterableOf<>("how", "are", "you", "?")
)
).value();Or even more compact:
new ForEach<>(
input -> System.out.printf(
"Item: %s\n", input
)
).exec(new IterableOf<>("how", "are", "you", "?"));To sort a list of words in the file:
List<Text> sorted = new ListOf<>(
new Sorted<>(
new Mapped<>(
text -> new ComparableText(text),
new Split(
new TextOf(
new File("/tmp/names.txt")
),
new TextOf("\\s+")
)
)
)
);To count elements in an iterable:
int total = new LengthOf(
new IterableOf<>("how", "are", "you")
).value().intValue();To create a set of elements by providing variable arguments:
final Set<String> unique = new SetOf<>(
"one",
"two",
"one",
"three"
);To create a set of elements from an existing iterable:
final Set<String> words = new SetOf<>(
new IterableOf<>("abc", "bcd", "abc", "ccc")
);To create a sorted iterable with unique elements from an existing iterable:
final Iterable<String> sorted = new Sorted<>(
new SetOf<>(
new IterableOf<>("abc", "bcd", "abc", "ccc")
)
);To create a sorted set from existing vararg elements using a comparator:
final Set<String> sorted = new org.cactoos.set.Sorted<>(
(first, second) -> first.compareTo(second),
"abc", "bcd", "abc", "ccc", "acd"
);To create a sorted set from an existing iterable using a comparator:
final Set<String> sorted = new org.cactoos.set.Sorted<>(
(first, second) -> first.compareTo(second),
new IterableOf<>("abc", "bcd", "abc", "ccc", "acd")
);This is a traditional foreach loop:
for (String name : names) {
System.out.printf("Hello, %s!\n", name);
}This is its object-oriented alternative (no streams!):
new And(
n -> {
System.out.printf("Hello, %s!\n", n);
return new True().value();
},
names
).value();This is an endless while/do loop:
while (!ready) {
System.out.println("Still waiting...");
}Here is its object-oriented alternative:
new And(
ready -> {
System.out.println("Still waiting...");
return !ready;
},
new Endless<>(booleanParameter)
).value();From our org.cactoos.time package.
Our classes are divided in two groups: those that parse strings into date/time objects, and those that format those objects into strings.
For example, this is the traditional way of parsing a string into an OffsetDateTime:
final OffsetDateTime date = OffsetDateTime.parse("2007-12-03T10:15:30+01:00");Here is its object-oriented alternative (no static method calls!)
using OffsetDateTimeOf, which is a Scalar:
final OffsetDateTime date = new OffsetDateTimeOf("2007-12-03T10:15:30+01:00").value();To format an OffsetDateTime into a Text:
final OffsetDateTime date = ...;
final String text = new TextOfDateTime(date).asString();| Cactoos | Guava | Apache Commons | JDK 17 |
|---|---|---|---|
And |
Iterables.all() |
- | - |
Filtered |
Iterables.filter() |
? | - |
FormattedText |
- | - | String.format() |
IsBlank |
- | StringUtils.isBlank() |
- |
Joined |
- | - | String.join() |
LengthOf |
- | - | String#length() |
Lowered |
- | - | String#toLowerCase() |
Normalized |
- | StringUtils.normalize() |
- |
Or |
Iterables.any() |
- | - |
Repeated |
- | StringUtils.repeat() |
- |
Replaced |
- | - | String#replace() |
Reversed |
- | - | StringBuilder#reverse() |
Rotated |
- | StringUtils.rotate() |
- |
Split |
- | - | String#split() |
StickyList |
Lists.newArrayList() |
? | Arrays.asList() |
Sub |
- | - | String#substring() |
SwappedCase |
- | StringUtils.swapCase() |
- |
TextOf |
? | IOUtils.toString() |
- |
TrimmedLeft |
- | StringUtils.stripStart() |
- |
TrimmedRight |
- | StringUtils.stripEnd() |
- |
Trimmed |
- | StringUtils.stripAll() |
String#trim() |
Upper |
- | - | String#toUpperCase() |
Ask your questions related to cactoos library on Stackoverflow with the cactoos tag.
Interfaces as the sole public abstraction.
Every primitive is declared as a Java @FunctionalInterface—Scalar<T>,
Text, Func<X,Y>, Input, Output, Bytes, and Proc—with no static
utility classes at this level.
This contrasts with Guava and Apache Commons, where
functionality is delivered through static methods on utility classes
(Iterables.filter(), StringUtils.isBlank()).
Because every concept is a real object, it can be subclassed, mocked, and
composed without reflection or special tooling.
Decorator pattern for all behavior extension.
Thread safety, memoization, null validation, and exception translation are
each added by wrapping one object in another, not by modifying the class.
Sticky<T> caches a Scalar<T> result; Synced<T> makes it thread-safe;
NoNulls rejects null inputs; Unchecked<T> rethrows checked exceptions
as unchecked ones.
This follows the Decorator pattern from GoF: every class has
exactly one responsibility, and capabilities are composed at call sites
rather than inherited.
Envelope pattern for safe inheritance.
Abstract base classes—IterableEnvelope, TextEnvelope, ScalarEnvelope,
and others—accept an inner object through the constructor and delegate to
it via final methods.
Concrete classes extend an envelope and supply only the inner object; no
method bodies are overridden.
This eliminates the fragile base class problem: because delegation
methods are final, a subclass cannot accidentally alter delegated behavior.
Lazy evaluation as the default.
No computation occurs until the caller explicitly requests it—.value(),
.asString(), or .iterator().
An IterableOf<> wrapping a transformation does no work until iterated.
This contrasts with Guava's ImmutableList.copyOf() and
Apache Commons Collections, which materialize elements at
construction time.
Explicit caching requires opting in with Sticky or StickyList.
Checked exceptions as first-class interface contracts.
All core interfaces declare throws Exception; the library never silently
converts checked exceptions to unchecked ones at the interface boundary.
When a caller needs unchecked access, it wraps with Unchecked<T> (rethrows
as UncheckedIOException), IoChecked<T> (narrows to IOException), or
Checked<T,E> (converts to any target exception type).
The decision about exception handling stays with the call site, not the library.
Zero runtime dependencies.
The library ships with no runtime dependencies.
Guava adds a ~3 MB JAR; Apache Commons splits across
multiple JARs (commons-lang3, commons-io, etc.).
Cactoos requires only JDK 17+, making it suitable for environments
where classpath size and dependency audits matter.
Just fork the repo and send us a pull request.
Make sure your branch builds without any warnings/issues:
mvn clean verify -PquliceTo run a build similar to the CI with Docker only, use:
docker run \
--tty \
--interactive \
--workdir=/main \
--volume=${PWD}:/main \
--volume=cactoos-mvn-cache:/root/.m2 \
--rm \
maven:3-eclipse-temurin-17 \
bash -c "mvn clean install -Pqulice; chown -R $(id -u):$(id -g) target/"To remove the cache used by Docker-based build:
docker volume rm cactoos-mvn-cacheNote: Checkstyle is used as a static code analysis tool with checks list in GitHub precommits.
- @yegor256 as Yegor Bugayenko (Blog)
- @g4s8 as Kirill Che.
- @fabriciofx as Fabrício Cabral
- @englishman as Andriy Kryvtsun
- @VsSekorin as Vseslav Sekorin
- @DronMDF as Andrey Valyaev
- @dusan-rychnovsky as Dušan Rychnovský (Blog)
- @timmeey as Tim Hinkes (Blog)
- @alex-semenyuk as Alexey Semenyuk
- @smallcreep as Ilia Rogozhin
- @memoyil as Mehmet Yildirim
- @llorllale as George Aristy
- @driver733 as Mikhail Yakushin
- @izrik as Richard Sartor
- @Vatavuk as Vedran Grgo Vatavuk
- @dgroup as Yurii Dubinka
- @iakunin as Maksim Iakunin
- @fanifieiev as Fevzi Anifieiev
- @victornoel as Victor Noël
- @paulodamaso as Paulo Lobo