In C#/.Net it is possible to join IEnumerable sequences with the extension method Enumerable.Join in a SQL 'JOIN ... ON' way.
Is there something similar in Java 8 (Stream API)? Or what is the best way to simulate Enumerable.Join?
See: https://msdn.microsoft.com/en-us/library/bb534675%28v=vs.100%29.aspx
In . NET, an easy way for you to simplify querying datasets is LINQ. Java doesn't have this, but since the introduction of Java 8 in 2014, you do now have the possibility to use "streams". Both LINQ and streams are ways to simplify querying datasets and to provide developers with an easy API to use.
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
All the Java Stream API interfaces and classes are in the java. util. stream package. Since we can use primitive data types such as int, long in the collections using auto-boxing and these operations could take a lot of time, there are specific classes for primitive types - IntStream , LongStream and DoubleStream .
With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.
join is just syntactic sugar for Stream.flatMap()
as explained in this article. Consider this example:
List<Integer> l1 = Arrays.asList(1, 2, 3, 4);
List<Integer> l2 = Arrays.asList(2, 2, 4, 7);
l1.stream()
.flatMap(i1 -> l2.stream()
.filter(i2 -> i1.equals(i2)))
.forEach(System.out::println);
The result is:
2
2
4
In the above example, flatMap()
corresponds to (INNER) JOIN
whereas the filter()
operation of the nested stream corresponds to the ON
clause.
jOOλ is a library that implements innerJoin()
and other join types to abstract over this, e.g. also to buffer stream contents in case you want to join two Stream
instances, instead of two Collection
instances. With jOOλ, you would then write:
Seq<Integer> s1 = Seq.of(1, 2, 3, 4);
Seq<Integer> s2 = Seq.of(2, 2, 4, 7);
s1.innerJoin(s2, (i1, i2) -> i1.equals(i2))
.forEach(System.out::println);
... which prints (the output are tuples, which is more like SQL's semantics semantics):
(2, 2)
(2, 2)
(4, 4)
(disclaimer, I work for the company behind jOOλ)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With