Contents

Java 8 Notes

Java 8 useful methods

List.sort()

1
2
3
4
List<String> list = ...
list.sort(null);                                    // use natural order
list.sort((s1, s2) -> s1.compareToIgnoreCase(s2));  // sort ignoring case
list.sort(String::compareToIgnoreCase);             // same with a method reference

List.removeIf()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
/* old way */
Iterator<String> it = list.iterator();
while(it.hasNext()) {
    String s = it.next();
    if (s.length() %2 == 0) {
        it.remove();
    }
}

/* java 8 */
list.removeIf(s -> s.length() % 2 == 0);

Map.getOrDefault()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
/* word count old way */
Map<String, Long> map = new HashMap<String, Long>();
for(String s: array) {
    Long count = map.get(s);
    map.put(s, (count == null)? 1L: count + 1);
}

/* java 8 */
Map<String, Long> map = new HashMap<>();
for(String s: args) {
    map.put(s, 1 + map.getOrDefault(s, 0L));
}

Map.computeIfAbsent()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* old way */
List<Person> people = ...
Map<String, List<Person>> byNameMap = new HashMap<>();
for(Person person: people) {
    String name = person.getName();
    List<Person> persons = byNameMap.get(name);
    if (persons == null) {
      persons = new ArrayList<>();
      byNameMap.put(name, persons);
    }
    persons.add(person);
}

/* java 8 */
Map<String, List<Person>> byNameMap = new HashMap<>();
for(Person person: people) {
    byNameMap.computeIfAbsent(person.getName(), name -> new ArrayList<>()).add(person);
}

/* more ... with stream */
Map<String, List<Person>> byNameMap =
people.stream().collect(Collectors.groupingBy(Person::getName));

/* implement a cache */
Map<Integer, FairlyBigObject> map = ...
map.computeIfAbsent(id, id -> DB.findById(FairlyBigObject.class, id));

Map.forEach()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
/* old way */
Map<String, List<Person>> byNameMap = ...
for(Map.Entry<String, List<Person>> entry: byNameMap.entrySet()) {
  System.out.println(entry.getKey() + ' ' + entry.getValue());
}

/* java 8 */
byNameMap.forEach((name, persons) -> {
  System.out.println(name + ' ' + persons);
});

Stream.filter()

1
2
3
/* java 8 */
List<Person> persons = 
Stream<Person> personsOver18 = persons.stream().filter(p -> p.getAge() > 18);

Stream.Collector

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
List<Student> students = persons.stream()
        .filter(p -> p.getAge() > 18)
        .map(Student::new)
        .collect(new Collector<Student, List<Student>>() {  });


List<Student> students = persons.stream()
        .filter(p -> p.getAge() > 18)
        .map(Student::new)
        .collect(Collectors.toList());

List<Student> students = persons.stream()
        .filter(p -> p.getAge() > 18)
        .map(Student::new)
        .collect(Collectors.toCollection(ArrayList::new));