Skip to content

Instantly share code, notes, and snippets.

@xpepper
Forked from Vashy/Java8Pills.md
Created March 4, 2021 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xpepper/3cd55bfad50db168af94ae2f295291f0 to your computer and use it in GitHub Desktop.
Save xpepper/3cd55bfad50db168af94ae2f295291f0 to your computer and use it in GitHub Desktop.
Java 8 pills

Java 8 Pills

Example class

@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;
}

Convert List<T> to List<U>

Example: convert a list of Users to a list of User.ids

// 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());
}

Convert List<T> to Map<U, V>

Example: convert a list of Users 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));
}

Filter List<T> and return a new List<T> with filtered elements

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());
}

Compute average from a filtered List<T>

Example: get average age from active Users.

// 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);
}

Find max element from a List<T> based on a given compare condition

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));
}

Sort elements of a Collection

Example: sort Users 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());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment