There are few ways to create Java stream objects from a typical collection or array data store. To use the Stream API, do the following steps:
- Let us create an experimental service class, EmployeeStreamService, which consists of service methods dedicated to stream methods. This first method only shows how to extract streams from employeeDaoImpl:
@Service("employeeStreamService") public class EmployeeStreamService { @Autowired private EmployeeDao employeeDaoImpl; public void getCollectionStreams(){ Stream<Employee> serial = employeeDaoImpl.getEmployees().stream(); Stream<Employee> parallel = employeeDaoImpl.getEmployees().parallelStream(); } }
- Next, add another method that illustrates how to extract stream data from an existing List<String> or Set<String> collection:
public void getListData(){ List<String> employeeIDS = Arrays.asList("23234", "353453", "22222", "5555", "676767"); Stream<String> streamsIds = employeeIDS.stream(); Set<String> candidates = new HashSet<String>(); candidates.add("Joel"); candidates.add("Candy"); candidates.add("Sherwin"); Stream<String> streamCandidates = candidates.stream(); }
- Lastly, the method below will show us how to extract a stream from an array of long, int, and double data:
public void getArrayData(){ int[] ages = {24, 33, 21, 22, 45}; IntStream ageStream = Arrays.stream(ages); double[] salaries = {33000.50, 23100.20, 45000.50}; DoubleStream salStream = Arrays.stream(salaries); long[] longDates = {23434432342L, 11123343435L, 34343342343L}; LongStream dateStream = Arrays.stream(longDates); }
- Save all files.
Always apply generics to stream objects to avoid explicit object conversion and some other type-related warnings.