I place here lambda constructions which I use most often.
- Get item by id
- "For" construction with lambda
- Select items using condition
- Filter items with paging
- Map entities to view model
- Create new Runnable
- Add ActionListener
// Get single person by id or null if does not exist
Person person = people.stream().filter(p -> p.getId() == 2)
.findFirst().orElse(null);
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()));
people.forEach(p -> p.setName(p.getName().trim()));
// Get people after 21
List<Person> adults = people.stream()
.filter(person -> person.getAge() >= 21)
.collect(Collectors.toList());
List<Person> adults = people.stream()
.filter(person -> person.getAge() >= 21)
.collect(Collectors.toList());
adults.forEach(p -> System.out.println(p.getName()));
// Select page 3 from 20 to 30 items
List<Person> page3 = people.stream().skip(20).limit(10).collect(Collectors.toList());
List<Person> page3 = people.stream().skip(20).limit(10).collect(Collectors.toList());
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());
.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()));
Runnable newRunnable = () -> {
System.out.println("New runnable");
};
newRunnable.run();
System.out.println("New runnable");
};
newRunnable.run();
// Lambda action listener
JButton lambdaButton = new JButton("Lambda button");
lambdaButton.addActionListener(e -> button.setText("I am pressed"));
JButton lambdaButton = new JButton("Lambda button");
lambdaButton.addActionListener(e -> button.setText("I am pressed"));