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 = people.stream().filter(p -> p.getId() == 2)
                .findFirst().orElse(null);

        System.out.println(person);

 

"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 = people.stream()
                .filter(person -> person.getAge() >= 21)
                .collect(Collectors.toList());

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

 

Filter items with paging:

        // Select page 3 from 20 to 30 items
        List<Person> page3 = people.stream().skip(20).limit(10).collect(Collectors.toList());

 

Map entities to view model

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

 

Create new Runnable

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

 

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.