DEV Community

Unpublished Post. This URL is public but secret, so share at your own discretion.

Avoid nesting/boilerplate in JAVA (map, reduce , filter)

Hi. This is just an example blog showcasing some ideas of avoiding nested loops by using java streams and functional programming concepts.

Note: This is a Work in Progress. more examples will be added

Some easy definitions:

map : is similar to a forEach loop. it will execute a function( described in map) for every element of your iterable and store results of that funtion in another iterable. it is a n->n mapping (every element in array will have a 1:1 mapping to its result)

filter: When you want to filter out array elements based on certain conditions hence producing an 'm' sized array from an 'n' sized array where m<=n, you use filter.

// deciding overlap of elements in another array example: find any versionOfFiles you have that's belonging to any unsupportedVersions
        Long[]  myArray = {1L,2L}, unsupportedVersionsArray = {1L,81L};
        myVersions= Sets.newHashSet(myVersionArray);
        Long[] deprecatedVersionsIHave = Arrays.stream(unsupportedVersionsArray).filter(myVersions::contains).toArray(Long[]::new);
        System.out.println(Arrays.toString(deprecatedVersionsIHave)); // returns [1L]
Enter fullscreen mode Exit fullscreen mode

reduce: When you want to reduce your array into a single object of same datatype, you use reduce (n->1). Eg: finding the maximum of all elements in an array.

Some alterations of reduce used in conditional checks are:

anyMatch: return True if any item in the array fulfilled the condition inside anyMatch

// ensuring absence of one array's elements in another array example: the versionOfFiles you have is not belonging to any unsupportedVersions
        Long[]  myVersionArray = {1L,2L}, unsupportedVersions = {20L,81L};
        HashSet<Long> myVersions= Sets.newHashSet(myVersionArray);
        boolean violation = Arrays.stream(unsupportedVersions).anyMatch(myVersions::contains);
Enter fullscreen mode Exit fullscreen mode

allMatch: return True only when all array elements match a condition mentioned in allMatch

Note: these functionalities are are present in python as well.

Top comments (0)