@Value // Lombok annotation.
// Generates all private final fields, an all-args-constructor,
// getters (no setters), toString(), etc...
class User {
String id;
String name;
boolean active;
int age;
int purchases;
}
Example: convert a list of User
s to a list of User.id
s
// Imperative approach
List<String> convert(List<User> users) {
List<String> ids = new ArrayList<>();
for (User user : users) {
ids.add(user.getId());
}
return ids;
}
// Functional approach
List<String> convert(List<User> users) {
return users.stream()
.map(User::getId)
.collect(Collectors.toList());
}
Example: convert a list of User
s to a map: { User.id: User }
// Imperative approach
Map<String, User> convertToMap(List<User> users) {
Map<String, User> map = new HashMap<>();
for (User user : users) {
map.put(user.getId(), user);
}
return map;
}
// Functional approach
Map<String, User> convertToMap(List<User> users) {
return users.stream().collect(Collectors.toMap(User::getId, user -> user));
}
Example: get users whose name starts with "A"
and their age is at least 18.
// Imperative approach
List<User> filter(List<User> users) {
List<User> list = new ArrayList<>();
for (User user : users) {
if (user.getName().startsWith("A") && user.getAge() >= 18) {
list.add(user);
}
}
return list;
}
// Functional approach
List<User> filter(List<User> users) {
return users.stream()
.filter(user -> user.getName().startsWith("N"))
.filter(user -> user.getAge() >= 18)
.collect(Collectors.toList());
}
Example: get average age from active User
s.
// Imperative approach
double average(List<User> users) {
int sum = 0;
int count = 0;
for (User user : users) {
if (user.isActive()) {
sum += user.getAge();
count++;
}
}
return count != 0 ? (double) sum / count : 0.0;
}
// Functional approach
double average(List<User> users) {
return users.stream()
.filter(User::isActive)
.mapToInt(User::getAge)
.average()
.orElse(0.0);
}
Example: get the User
with the maximum number of purchases.
// Imperative approach
User max(List<User> users) {
User maxUser = null;
int max = 0;
for (User user : users) {
if (user.getPurchases() > max) {
maxUser = user;
max = user.getPurchases();
}
}
return maxUser;
}
// Functional approach
Optional<User> max(List<User> users) {
return users.stream()
.max(Comparator.comparingInt(User::getPurchases));
}
Example: sort User
s by age
// Imperative approach
public List<User> sort2(List<User> users) {
// note that input list `users` gets modified
Collections.sort(users, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return Integer.compare(o1.age, o2.age);
}
});
return users;
}
// Functional approach
public List<User> sort1(List<User> users) {
return users.stream()
.sorted(comparingInt(user -> user.age))
.collect(toList());
}