Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/farolfo/list-comprehensions-in-java

(college project, see jComprehension for the lib) Build sets in mathematical set-builder notation with Java, like { x * 2 | x E {1,2,3,4} ^ x is even }
https://github.com/farolfo/list-comprehensions-in-java

Last synced: 3 months ago
JSON representation

(college project, see jComprehension for the lib) Build sets in mathematical set-builder notation with Java, like { x * 2 | x E {1,2,3,4} ^ x is even }

Awesome Lists containing this project

README

        

# List Comprehensions in Java
Build lists in mathematical [set-builder notation](https://en.wikipedia.org/wiki/Set-builder_notation) with Java, like { x * 2 | x E {1,2} ^ x is even }.

Used at: :D https://github.com/farolfo/JComprehension

### Usage and motivation

In algebra we are able to define sets using set-builder notation, also known as set comprehension or list comprehension. For example, this computes the even numbers in a set of integers

```java
{ x | x E {1,2,3,4} ^ x is even }
// gives {2,4}
```

which is read as _give me the set of all x such that x belongs to {1,2,3,4} and x is even_.

But this notation jumped out of algebra and today we have ways to do this in [many](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(list_comprehension)) programming languages, such as Haskell or python.

Now you can achieve this in Java

```java
Predicate even = x -> x % 2 == 0;

List evens = new ListComprehension()
.suchThat(x -> {
x.belongsTo(Arrays.asList(1, 2, 3, 4));
x.is(even);
});
// evens = {2,4};
```

And if we want to transform the output expression in some way like

```java
{ x * 2 | x E {1,2,3,4} ^ x is even }
// gives {4,8}
```

Our java code would look like

```java
List duplicated = new ListComprehension()
.giveMeAll((Integer x) -> x * 2)
.suchThat(x -> {
x.belongsTo(Arrays.asList(1, 2, 3, 4));
x.is(even);
});
// duplicated = {4,8}
```

### Further reading

* [Set-builder notation.](https://en.wikipedia.org/wiki/Set-builder_notation)
* [How are programming languages supporting this today?](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(list_comprehension))
* [Haskell's list comprehension](http://learnyouahaskell.com/starting-out#im-a-list-comprehension)

### License

MIT