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()){Strings=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=newHashMap<String,Long>();for(Strings:array){Longcount=map.get(s);map.put(s,(count==null)?1L:count+1);}/* java 8 */Map<String,Long>map=newHashMap<>();for(Strings:args){map.put(s,1+map.getOrDefault(s,0L));}
/* old way */List<Person>people=...Map<String,List<Person>>byNameMap=newHashMap<>();for(Personperson:people){Stringname=person.getName();List<Person>persons=byNameMap.get(name);if(persons==null){persons=newArrayList<>();byNameMap.put(name,persons);}persons.add(person);}/* java 8 */Map<String,List<Person>>byNameMap=newHashMap<>();for(Personperson:people){byNameMap.computeIfAbsent(person.getName(),name->newArrayList<>()).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);});