- Predicates are conditions!
- Consumers are actions!
- Comparators compare!
- Map transforms one thing to another!
- Create a generic method
filterList(List<T> list, Predicate<T> condition)
that returns a new list with only the elements that match the condition. - Test the method on a list of
Product
(as before) to filter:- i. Products under 100 kr.
- ii. Products that are in stock.
- iii. Combination with
.and()
.
- Create a generic method
forEachApply(List<T> list, Consumer<T> action)
that runsaction.accept()
on each element in the list. - Test with
Employee
objects where you:- i. Increase salaries by 10%.
- ii. Print information about all employees.
- Create a generic method
sortList(List<T> list, Comparator<T> comparator)
that sorts a list. - Test with
Book
objects:- i. Sort by year.
- ii. Sort by author.
- iii. Sort by year and then title.
- Extra: Create a method
maxBy(List<T>, Comparator<T>)
that returns the largest book according to a certain comparator.
- Make a list of
Student
. - Create a generic method
mapList(List<T> list, Function<T, R> mapper)
that converts a list of type T to a list of type R. - Filter (with Predicate) all those with grades > 70.
- Sort with Comparator by grade (highest first).
- Use
mapList
to convert the list ofStudent
to a list ofString
where each element is"Name: [name], Grade: [grade]"
.
- Create a generic method:
public static <T> void processItems(
List<T> list,
Predicate<T> filter,
Comparator<T> sorter,
Consumer<T> action
) {
// Code
}
- The method should:
- i. Filter the list with
Predicate
. - ii. Sort with
Comparator
. - iii. Run
Consumer
on each element.
- i. Filter the list with
- Test with a list
Order
(id
,customerName
,amount
,completed
). - Filter out only the incomplete orders.
- Sort them by amount (largest first).
- Print all with
Consumer
.