Skip to content

Commit b74e9be

Browse files
adding Java Stream
1 parent be8df21 commit b74e9be

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package com.thealgorithms.streamapi;
2+
import java.util.ArrayList;
3+
import java.util.HashSet;
4+
import java.util.List;
5+
import java.util.Set;
6+
import java.util.stream.Collectors;
7+
8+
/*
9+
What is Collection Framework ..?
10+
- To Store or manipulate group of objects, we use Collection Framework.
11+
- Different types of Collections are List, Set, Map and Queue.
12+
13+
What is Stream ..?
14+
- Stream is a pipeline of functions which allows you to perform operations such as filtering, mapping, and reducing on a collection of data.
15+
*/
16+
17+
18+
public class Stream{
19+
20+
public static void main (String args []){
21+
22+
// Suppose we have a List of Data and we wanted to convert it into Set.
23+
List<Integer> arrayList = List.of(0, 1, 1, 2, 3, 5, 3, 2, 7, 4, 9, 8, 12, 19, 6, 11, 18) ;
24+
25+
26+
// Here, we are expecting to filter all those elements from list which are even.
27+
List<Integer> evenList = evenElementList(arrayList) ;
28+
29+
// Here, we are expecting to convert each element to its square value.
30+
List<Integer> squareList = convertToSquare(arrayList) ;
31+
32+
// Here, we are expecting to receive first 5 elements from arrayList.
33+
List<Integer> first5element = getLimitedElements(arrayList, 5);
34+
35+
// Here, we are expecting to store the List elements into Set.
36+
Set<Integer> arraySet = convertListToSet(arrayList) ;
37+
38+
}
39+
40+
41+
42+
43+
44+
45+
/*
46+
This Method return all the even elements.
47+
Take Argument as List.
48+
Return List of elements divisible by 2.
49+
*/
50+
public static List<Integer> evenElementList(List<Integer> arrayList){
51+
return arrayList.stream().filter((element)->{return element%2==0;}).collect(Collectors.toList()) ;
52+
}
53+
54+
55+
/*
56+
This Method return all the even elements.
57+
Take Argument as List.
58+
Return List of elements*element.
59+
*/
60+
public static List<Integer> convertToSquare(List<Integer> arrayList){
61+
return arrayList.stream().map((element)->{return element*element;}).collect(Collectors.toList()) ;
62+
}
63+
64+
65+
/*
66+
This Method return all the even elements.
67+
Take Argument as List and number of elements needed to be returned.
68+
Return List of n number of elements.
69+
*/
70+
public static List<Integer> getLimitedElements(List<Integer> arrayList, int size){
71+
return arrayList.stream().limit(size).collect(Collectors.toList()) ;
72+
}
73+
74+
75+
/*
76+
This Method convert List to Set.
77+
Take Argument as List.
78+
Return Set of elements.
79+
*/
80+
public static Set<Integer> convertListToSet (List<Integer> arrayList) {
81+
return arrayList.stream().map(eachElement -> eachElement).collect(Collectors.toSet()) ;
82+
}
83+
}

0 commit comments

Comments
 (0)