| Collection | 有stream()方法 |
| Array | Arrays.stream(...) |
| Map | Map.entrySet().stream() |
Stream中的方法
| 方法 | 说明 |
|---|
| Stream filter(Predicate super T> predicate); | 数据过滤,保留满足条件的 |
| Stream map(Function super T, ? extends R> mapper); | 数据映射,T → R |
| Stream distinct(); | 数据去重,与对象的equals()方法有关 |
| Stream sorted(); | 数据排序,对象需实现Comparable接口 |
| Stream sorted(Comparator super T> comparator); | 数据排序,Comparator |
| Stream peek(Consumer super T> action); | 数据流结束之后才会执行 |
| Stream limit(long maxSize); | 数据过滤 |
| Stream skip(long n); | 跳过n个数据 |
| void forEach(Consumer super T> action); | 数据流结束操作 |
| A[] toArray(IntFunction generator); | 转变为A[]数组 |
| T reduce(T identity, BinaryOperator accumulator); | |
| R collect(Collector super T, A, R> collector); | 使用收集器收集数据 |
| Optional min(Comparator super T> comparator); | 最小值 |
| Optional max(Comparator super T> comparator); | 最大值 |
| long count(); | 计数 |
| boolean anyMatch(Predicate super T> predicate); | |
| boolean allMatch(Predicate super T> predicate); | |
| boolean noneMatch(Predicate super T> predicate); | |
| Optional findFirst(); | Optional ,Stream中的一个数据 |
| Optional findAny(); | |
| public static Stream of(T t); | |
| public static Stream of(T... values); | |
数据排序Comparator数据收集Collectors
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("A",5);
map.put("B",1);
map.put("C",6);
String collect = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.map(Map.Entry::getKey)
.collect(Collectors.joining(","));
System.out.println(collect);
}
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("A",5);
map.put("B",1);
map.put("C",6);
map.put("D",1);
Map>> collect = map.entrySet().stream()
.collect(Collectors.groupingBy(Map.Entry::getValue));
}
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("A",5);
map.put("B",1);
map.put("C",6);
map.put("D",1);
Map collect = map.entrySet().stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.counting()));
}
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("A",5);
map.put("B",1);
map.put("C",6);
map.put("D",1);
Map> collect = map.entrySet().stream()
.collect(Collectors.groupingBy(Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.toSet())));
}
Optional
public static void main(String[] args) {
boolean present = Optional.ofNullable(null).isPresent();
String o = Optional.ofNullable("B").filter("A"::equals).orElse("***");
System.out.println(present);
System.out.println(o);
}