Java arrays and collections are a core part of any Java program. Almost every Java application makes use of arrays or collections to process data, group data, summarize data and gather intelligence from data.
But processing data from arrays or collections, filtering data, grouping data and summarizing data is not perfect. You will end up writing multiple loops leading to complex code.
Streams API, introduced in Java 8, extensively simplifies and reduces the lines of code needed to process data from collections, by providing a declarative and functional-style operations to process data. In addition, operations can be chained together to form a pipeline which would have required multiple loops prior to Java 8.
You may not be asked specific questions on Streams, but your knowledge of using Streams to process data is absolutely necessary to excel in coding sessions.
Below we will see how to use Streams for performing some common data operations. For data, we will use a list of 'State' objects as example. Each 'State' object contains attributes 'code', 'name', and list of 'City' objects. 'City' contains attributes 'name' and 'population'.
//List of states
List<State> stateList = Util.buildStateList();
//Print list of states codes
stateList
.stream()
.forEach(e -> {System.out.println(e.getStateCode()));}
//List of states
List<State> stateList = Util.buildStateList();
//Filter states and print state codes
stateList
.stream()
.filter(e -> e.getStateCode().startsWith('A'))
.forEach(e -> {System.out.println(e.getStateCode()));}
//List of states
List<State> stateList = Util.buildStateList();
//Filter states and print state codes
stateList
.stream()
.filter(e -> e.getStateCode().startsWith('A'))
.map(e -> e.getStateName().toUpperCase())
.forEach(e -> {System.out.println(e.getStateName()));}
*** See complete answer and code snippet in the Java Interview Guide.
*** See complete answer and code snippet in the Java Interview Guide.
*** See complete answer and code snippet in the Java Interview Guide.