• Stars
    star
    722
  • Rank 60,380 (Top 2 %)
  • Language
    Java
  • License
    MIT License
  • Created almost 7 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Object-Oriented Java primitives, as an alternative to Google Guava and Apache Commons

logo

EO principles respected here DevOps By Rultor.com We recommend IntelliJ IDEA

mvn Javadoc PDD status Maven Central License Test Coverage SonarQube Hits-of-Code Codacy Badge

Project architect: @victornoel

ATTENTION: We're still in a very early alpha version, the API may and will change frequently. Please, use it at your own risk, until we release version 1.0. You can view our progress towards this release here.

Cactoos is a collection of object-oriented Java primitives.

Motivation. 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.

Principles. These are the design principles behind Cactoos.

How to use. The library has no dependencies. All you need is this (get the latest version here):

Maven:

<dependency>
  <groupId>org.cactoos</groupId>
  <artifactId>cactoos</artifactId>
  <version>0.55.0</version>
</dependency>

Gradle:

dependencies {
  compile 'org.cactoos:cactoos::0.55.0
}

Java version required: 1.8+.

StackOverflow tag is cactoos.

Input/Output

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();

Text/Strings

To format a text:

String text = new FormattedText(
  "How are you, %s?",
  name
).asString();

To manipulate with a text:

// To lower case
new Lowered(
	new TextOf("Hello")
);
// To upper case
new Upper(
	new TextOf("Hello")
);

Iterables/Collections/Lists/Sets

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<String>(
    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<String>(
    "one",
    "two",
    "one",
    "three"
);

To create a set of elements from existing iterable:

final Set<String> words = new SetOf<>(
    new IterableOf<>("abc", "bcd", "abc", "ccc")
);

To create a sorted iterable with unique elements from 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 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 existing iterable using comparator:

final Set<String> sorted = new org.cactoos.set.Sorted<>(
    (first, second) -> first.compareTo(second),
    new IterableOf<>("abc", "bcd", "abc", "ccc", "acd")
);

Funcs and Procs

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();

Dates and Times

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();

Our objects vs. their static methods

Cactoos Guava Apache Commons JDK 8
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()

Questions

Ask your questions related to cactoos library on Stackoverflow with cactoos tag.

How to contribute?

Just fork the repo and send us a pull request.

Make sure your branch builds without any warnings/issues:

mvn clean verify -Pqulice

To 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-jdk-8 \
	bash -c "mvn clean install site -Pqulice -Psite --errors; chown -R $(id -u):$(id -g) target/"

To remove the cache used by Docker-based build:

docker volume rm cactoos-mvn-cache

Note: Checkstyle is used as a static code analyze tool with checks list in GitHub precommits.

Contributors

More Repositories

1

tacit

CSS framework for dummies, without a single CSS class: nicely renders properly formatted HTML5 pages
SCSS
1,636
star
2

takes

True Object-Oriented Java Web Framework without NULLs, Static Methods, Annotations, and Mutable Objects
Java
777
star
3

rultor

DevOps team assistant that helps you merge, deploy, and release GitHub-hosted apps and libraries
Java
468
star
4

qulice

Quality Police for Java projects: aggregator of Checkstyle and PMD
Java
293
star
5

s3auth

Amazon S3 HTTP Basic Auth Gateway: put your files into S3 bucket and make them accessible with a login/password through a browser
Java
254
star
6

xembly

Assembly for XML: an imperative language for modifying XML documents
Java
236
star
7

jare

Free and Instant Content Delivery Network (CDN)
Java
130
star
8

elegantobjects.github.io

Fan club for Elegant Objects programmers
HTML
111
star
9

iri

Simple Immutable URI/URL Builder in Ruby
Ruby
110
star
10

0pdd

Puzzle Driven Development (PDD) Chatbot Assistant for Your GitHub Repositories
Ruby
109
star
11

blog

My blog about computers, written in Jekyll and deployed to GitHub Pages
Liquid
108
star
12

quiz

Refactor the code to make it look more object-oriented and maintainable
PHP
104
star
13

dynamo-archive

Archive and Restore DynamoDB Tables, from the Command Line
JavaScript
100
star
14

jekyll-github-deploy

Jekyll Site Automated Deployer to GitHub Pages
Ruby
78
star
15

sixnines

Website Availability Monitor: add your website to our dashboard and get 24x7 monitoring of its availability (and a badge!)
Ruby
68
star
16

hoc

Hits-of-Code Command Line Calculator, for Git and Subversion
Ruby
61
star
17

ssd16

16 lectures about "Software Systems Design" presented in Innopolis University in 2021 for 3rd year BSc students
TeX
57
star
18

squid-proxy

Docker image for a Squid forward proxy with authorization (fully anonymous)
Dockerfile
52
star
19

jekyll-plantuml

PlantUML plugin for Jekyll: helps you embed UML diagrams into static pages
Ruby
43
star
20

xdsd

eXtremely Distributed Software Development
TeX
41
star
21

jpages

Experimental Java OOP Web Framework
Java
39
star
22

rehttp

HTTP Repeater: you point your Webhooks to us and we make sure they get delivered even if not on the first try
Java
39
star
23

netbout

Private talks made easy
Java
39
star
24

awesome-risks

Sample Risks for a Software Project
38
star
25

requs

Controlled Natural Language for Requirements Specifications
Java
37
star
26

cactoos-http

Object-Oriented HTTP Client
Java
36
star
27

threecopies

Hosted Server Backup Service
Java
36
star
28

awesome-academic-oop

Curated list of academic writings on object-oriented programming
35
star
29

threads

Ruby Gem to unit-test a piece of code in multiple concurrent threads
Ruby
35
star
30

zache

Zero-footprint Ruby In-Memory Thread-Safe Cache
Ruby
34
star
31

mailanes

Smart E-mail Delivery System
Ruby
33
star
32

codexia

Open Source Incubator
Ruby
33
star
33

micromap

๐Ÿ“ˆ A much faster (for very small maps!) alternative of Rust HashMap, which doesn't use hashing and doesn't use heap
Rust
31
star
34

hangman

Hangman (the game) written in a very unelegant procedural style, which you can improve in order to test your skills
Java
29
star
35

jacli

Java Command Line Interface
29
star
36

wring

Smart Inbox for GitHub Notifications
Java
27
star
37

sibit

Simplified Command-Line Bitcoin Client
Ruby
27
star
38

xcop

Command Line Style Checker of XML Documents
Ruby
27
star
39

phprack

phpRack Integration Testing Framework
PHP
25
star
40

thindeck

Web Hosting That Deploys Itself
Java
24
star
41

elegantobjects

Supplementary materials for "Elegant Objects" book
Java
22
star
42

jekyll-git-hash

Jekyll Plugin for Git Hash Retrieval
Ruby
21
star
43

painofoop

Object-oriented programming is a pain if we do it wrong: Lecture Notes for a BSc course
TeX
21
star
44

0rsk

Online Risk Manager
Ruby
20
star
45

tojos

Text Object Java Objects (TOJOs): an object representation of a multi-line structured text file like CSV, YAML, or JSON
Java
19
star
46

soalition

Social Coalitions of Internet Writers
Ruby
18
star
47

jo

Junior Objects: JavaScript Examples
JavaScript
17
star
48

random-port

A Ruby gem to reserve a random TCP port
Ruby
17
star
49

latex-best-practices

A short collection of LaTeX academic writing best practices: it's my personal taste, read it skeptically
TeX
17
star
50

total

Ruby Gem to get total memory size in the system
Ruby
16
star
51

backtrace

Ruby gem to print exception backtrace nicely
Ruby
16
star
52

telepost

Simple Telegram posting Ruby gem
Ruby
15
star
53

rexsl

Java RESTful XSL-based Web Framework
Java
15
star
54

ru.yegor256.com

My Russian blog about politics and social problems
HTML
15
star
55

huawei.cls

LaTeX class for documents you create when working with Huawei or maybe even inside it
TeX
14
star
56

glogin

Login/logout via GitHub OAuth for your Ruby web app
Ruby
14
star
57

seedramp

Micro-Investment Venture Fund
HTML
14
star
58

use_tinymce

yet another TinyMCE for Rails adaptor. Rails 3 + Minimal dependencies
JavaScript
14
star
59

tacky

Primitive Object Memoization for Ruby
Ruby
14
star
60

nutch-in-java

How to use Apache Nutch without command line
Java
14
star
61

futex

File-based Ruby Mutex
Ruby
14
star
62

veils

Ruby Veil Objects
Ruby
13
star
63

texsc

Spell checking for LaTeX documents with the help of aspell
Ruby
13
star
64

bloghacks

Jekyll demo blog for "256 Bloghacks" book
HTML
13
star
65

cam

Classes and Metriัs (CaM): a dataset of Java classes from public open-source GitHub repositories
Shell
13
star
66

latexmk-action

GitHub action for building LaTeX documents via latexmk
Dockerfile
13
star
67

rumble

Command Line Tool to Send Newsletters
Ruby
13
star
68

est

Estimates Automated
Ruby
12
star
69

syncem

A simple Ruby decorator to make all methods of your object thread-safe
Ruby
12
star
70

techiends

Tech Friends Club
HTML
12
star
71

loog

Ruby object, which you can pass to other objects, where they will use it as a logger
Ruby
12
star
72

fibonacci

Fibonacci algorithm implemented in a few compilable languages in different programming flavors
C++
12
star
73

drops

Primitive CSS classes to replace most commonly used CSS styles
CSS
12
star
74

kdpcover

LaTeX class rendering a cover for a book published by Kindle Direct Publishing (KDP)
TeX
12
star
75

iccq.github.io

Official Website of International Conference on Code Quality (ICCQ)
TeX
12
star
76

ppt-slides

LaTeX package for making slide decks ร  la PowerPoint (PPT)
TeX
12
star
77

dockers

Useful Docker Images
Dockerfile
11
star
78

obk

Ruby decorator to throttle object method calls: there will be fixed delays between them
Ruby
11
star
79

xsline

Declarative and Immutable Java Chain of XSL Transformations
Java
11
star
80

microstack

The most primitive and the fastest implementation of a fixed-size last-in-first-out stack on stack in Rust, for Copy-implementing types
Rust
11
star
81

jaxec

Primitive execution of command line commands from Java (mostly useful for tests)
Java
11
star
82

jekyll-chatgpt-translate

Automated translating of Jekyll pages via ChatGPT: all you need is just an OpenAI API key
Ruby
10
star
83

phandom

PhantomJS Java DOM Builder
Java
10
star
84

tdx

Test Dynamics
Ruby
10
star
85

texqc

LaTeX Build Quality Control: checks the log file after LaTeX and finds error reports
Ruby
10
star
86

names-vs-complexity

How compound variable names affect complexity of Java methods
TeX
10
star
87

random-tcp-port

Random TCP Port Reserver
C++
10
star
88

jekyll-bits

Jekyll plugin with simple and nice tools for better blogging
Ruby
10
star
89

articles

Some articles I write for online and offline magazines
Perl
9
star
90

yb-book

This LaTeX class I'm using for all my books I publish on Amazon
TeX
9
star
91

bibrarian

Quotes Organized
Java
9
star
92

size-vs-immutability

Empirically proven that immutable Java classes are smaller than mutable ones
TeX
9
star
93

rultor-image

Default Docker image for Rultor
Dockerfile
9
star
94

rultor-remote

Rultor command line remote control
Ruby
9
star
95

colorizejs

jQuery plugin to colorize data elements
JavaScript
9
star
96

emap

๐Ÿ“ˆ The fastest map possible in Rust, where keys are integers and the capacity is fixed (faster than Vec!)
Rust
9
star
97

pgtk

PostgreSQL ToolKit for Ruby apps: Liquibase + Rake + Connection Pool
Ruby
8
star
98

jpeek-maven-plugin

Maven Plugin for jPeek
Java
8
star
99

fazend-framework

FaZend Framework, Zend Framework extensions
PHP
8
star
100

sqm

Lecture Notes for "Software Quality Metrics" course in HSE University, 2023-2024
TeX
8
star