1. group by 使用
class BlogPost {
String title;
String author;
BlogPostType type;
int likes;
}
List<BlogPost> posts = Arrays.asList( ... );
Map<BlogPostType,List<BlogPost>> postsPerType=posts.stream().collect(groupingBy(BlogPost::getType))
Map<Tuple,List<BlogPost>>postsPerTypeAndAuthor =posts.stream().collect(groupingBy(post -> new Tuple(post.getType(), post.getAuthor())))
Map<Integer, Set<String>> result = givenList.stream()
.collect(groupingBy(String::length, toSet()));
2. list to Map 使用
class Book {
private String name;
private int releaseYear;
private String isbn;
// getters and setters
}
public Map<String,String> listToMap(List<Book> books){
return book.stream().collect(Collects.toMap(Book::getIsbn, Book::getName))
}
Map<String, Integer> result = givenList.stream()
.collect(toMap(Function.identity(), String::length))
3. reduce 使用
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result=numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
int result = numbers.stream().reduce(0, Integer::sum);
4.forEach()
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
ins.stream().forEach(i->{
if (i.intValue() % 2 == 0) {
Assert.assertTrue(i.intValue() % 2 == 0);
} else {
Assert.assertTrue(i.intValue() % 2 != 0);
}
})
4.Collectors 使用
List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
List<String> result = givenList.stream()
.collect(toList());
Set<String> result = givenList.stream()
.collect(toSet()); // 去掉重复的
List<String> result = givenList.stream().collect(toCollection(LinkedList::new))
String result = givenList.stream()
.collect(joining()); // "abbcccdd"
String result = givenList.stream()
.collect(joining(" "));
String result = givenList.stream()
.collect(joining(" ", "PRE-", "-POST"));
5. stream
long count = list.stream().distinct().count();
for (String string : list) {
if (string.contains("a")) {
return true;
}
}
boolean isExist = list.stream().anyMatch(element -> element.contains("a"));
List<String> resultList
= list.stream().map(element -> element.toUpperCase()).collect(Collectors.toList());