Java 8 | Writing custom Stream API using builder pattern

In this post we are going to create simple Java 8 Stream API using builder pattern. Check builder pattern post here

API will provide below four methods -
  1. sort - Sort the list
  2. limit - Fetch only N numbers from the list
  3. distinct - Remove duplicates from the list
  4. forEach - Print the list
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.lang.Integer;
interface CustomStreamApi<U extends Comparable> {
CustomStreamApi<U> sort();
CustomStreamApi<U> limit(long size);
CustomStreamApi<U> distinct();
void forEach();
}
public class CustomStream<T extends Comparable> implements CustomStreamApi<T> {
private List<T> list;
CustomStream(List<T> list) {
this.list = list;
}
@Override
public void forEach() {
for(T t : this.list) {
System.out.println(t);
}
}
@Override
public CustomStream sort() {
Collections.sort(this.list);
return this;
}
@Override
public CustomStream limit(long size) {
List<T> newList = new ArrayList<>();
int count = 0;
for(T integer : this.list) {
if(count > size) {
break;
}
newList.add(integer);
count++;
}
this.list = newList;
return this;
}
@Override
public CustomStream distinct() {
List<T> newList = new ArrayList<>();
for(T integer : this.list) {
if(newList.contains(integer)) {
continue;
}
newList.add(integer);
}
this.list = newList;
return this;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("CustomStream{");
sb.append("list=").append(list);
sb.append('}');
return sb.toString();
}
public static <T extends Comparable> CustomStream stream(List<T> integerList) {
return new CustomStream(integerList);
}
public static void main(String[] args) {
List<Integer> integers = new ArrayList<>();
integers.add(1);
integers.add(2);
integers.add(1);
integers.add(5);
integers.add(5);
integers.add(6);
integers.add(4);
integers.add(0);
CustomStream.stream(integers).sort().distinct().limit(3).forEach();
List<Double> doubles = new ArrayList<>();
doubles.add(1.1);
doubles.add(2.1);
doubles.add(1.1);
doubles.add(5.1);
doubles.add(5.1);
doubles.add(6.1);
doubles.add(4.1);
doubles.add(0.1);
CustomStream.stream(doubles).sort().distinct().limit(3).forEach();
}
}

Comments

Popular posts from this blog

Spring | Using TIBCO EMS with Spring framework

TIBCO | For Loop - Accumulate output

TIBCO | JNDI Server & JMS Instance creation