Gradle Setup :
build.gradle(Module: app)
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
jackOptions {
enabled true
}
What is the Stream API ?
Advantage's:
How streams work :
Normal Approach (Without using Stream Api) :
List<Integer> numbers = new ArrayList<>();
numbers.addAll(Arrays.asList(1, 20, 3, 10, 20, 30, 4, 50, 80, 1, 2));//adding dummy data
int i = 0;
List<String> number_str = new ArrayList<>();
for (Integer num : numbers) {
if (i >= 5)//after 5 loop will stop
break;
if (num >= 10) // check number greater than or equal to 10
{
number_str.add(String.format("Number %d", num));//Typecast Integer to String then add to String List
i++;//increment i count
}
}
number_str.sort(Comparator.naturalOrder());//sort the list
i >= 5
) and num >=10
. finally sort the string list.Now, let’s rewrite the code using Java’s 8 Stream API:
List<Integer> numbers = new ArrayList<>();
numbers.addAll(Arrays.asList(1, 20, 3, 10, 20, 30, 4, 50, 80, 1, 2));
List<String> number_str = numbers.stream()
.filter(num -> num >= 10)//check num greater than 10
.limit(5)//stop loop at 5
.sorted()//sort the list
.map(num -> String.format("Number %d", num))//typecast into String List
.collect(Collectors.toList());