Trying Java Streams
Streams in Java enables us to filter, sort, map, count and loop over elements in collections.
For this example, we use a Record type, a Java 14 feature to represent a static website generator.
record StaticWebsiteGenerator(
String name,
String language,
String license,
int stars
) {}
We then create instances for each type of static website generator and store them within a list:
StaticWebsiteGenerator swgNextJs = new StaticWebsiteGenerator("Next.js", "JavaScript", "MIT", 84087);
StaticWebsiteGenerator swgHugo = new StaticWebsiteGenerator("Hugo", "Go", "Apache 2.0", 58055);
StaticWebsiteGenerator swgGatsby = new StaticWebsiteGenerator("Gatsby", "JavaScript", "MIT", 52632);
StaticWebsiteGenerator swgGatsby2 = new StaticWebsiteGenerator("Gatsby", "JavaScript", "MIT", 52632);
StaticWebsiteGenerator swgJekyll = new StaticWebsiteGenerator("Jekyll", "Ruby", "MIT", 44409);
List<StaticWebsiteGenerator> lstSwg = Arrays.asList(swgNextJs, swgHugo, swgGatsby, swgGatsby2, swgJekyll);
The .stream() method gives us a stream that we can use to process the elements. The .filter() method takes a lambda expression and only takes elements that evaluate to true through the lambda function. The .sorted() passes 2 object instances to the lambda and this is easily handled by calling .compareTo. The .map() method transforms the source elements - in this case, we get the names of the static website generators as strings in the resulting List.
List<String> lstSwgNames = lstSwg.stream()
.filter(swg -> swg.language == "JavaScript")
.sorted( (x,y) -> x.name.compareTo(y.name) )
.map(swg -> "[" + swg.name + "]")
.collect(Collectors.toList())
;
We then process the List of String objects to keep only unique values and iterate over them in a loop that prints the Strings:
lstSwgNames.stream()
.distinct()
.forEach(iterstr -> System.out.println(iterstr));
Streams can also be used for performing the equivalent of a SELECT-GROUP BY like this:
Map<String, Long> swgByLicense = lstSwg.stream()
.collect(
Collectors.groupingBy(
StaticWebsiteGenerator::license,
//Collectors.toList(),
Collectors.counting()
)
)
;
for(Map.Entry<String, Long> entry : swgByLicense.entrySet()) {
System.out.println(
entry.getKey() +
" - " +
entry.getValue().toString()
);
}
Data can also be reduced with the .reduce() or the short-hand methods: .min(), .max(), .average().