Lambda examples

I place here lambda constructions which I use most often.

Get item by id:

        // Get single person by id or null if does not exist
        Person person = -> p.getId() == 2)



"For" construction with lambda:

        // Iterate through all collection, correct white spaces in names
        people.forEach(p -> p.setName(p.getName().trim()));


Filter items using condition:

    // Get people after 21
        List<Person> adults =
                .filter(person -> person.getAge() >= 21)

        adults.forEach(p -> System.out.println(p.getName()));


Filter items with paging:

        // Select page 3 from 20 to 30 items
        List<Person> page3 =;


Map entities to view model

        List<PersonViewModel> infoList = people
                .map(p -> new PersonViewModel(p.getId(), 
                        // Set view model short title
                        // Set view model full info
                        String.format("Name: %s. Age:%d ", p.getName(), p.getAge())))
        infoList.forEach(view -> System.out.println(view.getInfo()));


Create new Runnable

        Runnable newRunnable = () -> {
            System.out.println("New runnable");


Add action listener

        // Lambda action listener
        JButton lambdaButton = new JButton("Lambda button");
        lambdaButton.addActionListener(e -> button.setText("I am pressed"));


Leave a Reply

Your email address will not be published.