Skip to content

Instantly share code, notes, and snippets.

@dmorgan-github
Created July 16, 2014 21:06
Show Gist options
  • Save dmorgan-github/752d751869a5c997b37e to your computer and use it in GitHub Desktop.
Save dmorgan-github/752d751869a5c997b37e to your computer and use it in GitHub Desktop.
Group by in Java 8 using streams and lambdas
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Application {
public static void main(String[] args) {
List<String> l = new ArrayList(Arrays.asList("one", "two", "three"));
Map<Integer, Long> result = l.stream()
.collect(Collectors.groupingBy((String str) -> str.length(), Collectors.counting()));
System.out.print(result);
//{3=2, 5=1}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment