Java Map And Filter, A lambda or anonymous expression example

java lambda expression
Java lambda expression 

It’s been a while since JDK 8 release, since that version of Java the language, it adopted many new nicer syntax, the one that i love is the Lambda expressions. 

Lambda or anonymous function can make you write in a nice looking functional one liner code, for example below is a Java way of looking for keywords if they match in an Array, true if match and false otherwise.

//given array
List<String> words = Arrays.asList( "foo", "bar", "cool" );
//check if 'cool' exists
boolean isCool = words.stream().anyMatch(word -> word.equals("cool"));

1. Map

Map objects to another value as specified by a Function object, example below to Reduce List of object Person, to just List of person names.

2. Filter

Filter objects that match a Predicate object. Example below is an example to filter people with certain age.

import lombok.Data;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class ExampleJavaClass {
    private static final Logger logger = Logger.getLogger(ExampleJavaClass.class.getName());
    static List<Person> PEOPLE = Arrays.asList(
            new Person("Adam", 24),
            new Person("Conan", 55),
            new Person("Roger", 18),
            new Person("Seth", 40)
    );
    public static void main(String[] args) {
        try {
            //find person by name and print
            System.out.println( ExampleJavaClass.getPersonByName ("adam") );
            //collect all person names and print
            System.out.println( ExampleJavaClass.getPersonNames () );
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
    }
    static List<String> getPersonNames() throws Exception {
        //example map in Java
        return PEOPLE.stream()
                .map(Person::getName)
                .collect(Collectors.toList());
    }
    static Person getPersonByName(String name) throws Exception {
        //example filter in Java
        return PEOPLE.stream()
                .filter( person -> person.getName().equalsIgnoreCase( name ) )
                .collect(Collectors.toList())
                .get(0);
    }
    @Data
    public static class Person{
        final private String name;
        final private Integer age;
    }
}

In the example above, if you see the annotation @Data in the example above, i use a cool Java library called Lombok, so i don’t need to write Constructor, setter and getter in a class person. (project lombok can be found at https://projectlombok.org/)

You can do more cool, somewhat tricky Lambda stuff in Java, but mostly I only use it for array mapping, filtering, and finding if it contains something, other than that I am still kind of struggling. But don’t worry though, there’s Stackoverflow ready to help. 

And if you are using an Advanced IDE like Intellij IDEA, it will provide you a code assistant to do the best possible lambda in Java. (Intellij IDEA can be download at https://www.jetbrains.com/idea/)

Java is an old fashioned yet still reliable language to use in our software development. It has lots of advantages to use it than any other language like a general purpose language which means you can use Java from web application, mobile even a real world application to talk on hardware level. 

It’s also cross platform meaning, you can write single code and can run on any platform, and it certainly has millions of useful libraries ready to use for free.

Popular posts from this blog

ERROR 1348 Column Password Is Not Updatable When Updating MySQL Root Password

How To Create Spring Boot Project Using Netbeans

Spring Kafka - How to use ReplyingKafkaTemplate send and reply synchronously