初始化测试数据
private List<String> strings = Arrays.asList("abc", "0", "bc", "for","bc", "e fg", "jse", "Ff", "jkl","886");
1.获取流对象
Stream<String> stream = strings.stream();
Stream<String> stringStream = strings.parallelStream();
Collection<String> list = new ArrayList<>();
Stream<String> s = list.stream();
Map<Integer, String> map = new HashMap<>();
Stream<Integer> keyStream = map.keySet().stream();
Stream<String> valueStream = map.values().stream();
Stream<Map.Entry<Integer, String>> keyAndValueStream = map.entrySet().stream();
String[] names = {"1", "2"};
Stream<String> namesStream = Arrays.stream(names);
Stream<String> stringStream = Stream.of(names);
2.foreach
作用:遍历集合
names.forEach(System.out::println);
3.collect
作用:收集器,能够将流转换为其他形式,比如:list set map
Set<String> set = strings.stream().collect(Collectors.toSet());
Map<String, String> toMap = strings.stream().collect(Collectors.toMap(v -> "prod_" + v, v -> v, (oldValue, newValue) -> newValue));
Map<String, Student> studentMap = students.stream().collect(Collectors.toMap(student -> student.getId().toString(), student -> student));
Map<String, List<Student>> studentListMap = students.stream().collect(Collectors.groupingBy(student -> String.valueOf(student.getAge())));
4.filte
作用:用于通过设置的条件过滤出元素
List<String> filterStrings = strings.stream().filter(str -> str.contains("f")).collect(Collectors.toList());
List<Student> filterStudents = students.stream().filter(student -> 18 == student.getAge()).collect(Collectors.toList());
5.distinct
作用:去除集合中重复的元素
List<String> distinct = strings.stream().distinct().collect(Collectors.toList());
6.limit
作用:获取流中前 n 元素
List<String> limitStrings = strings.stream().limit(2).collect(Collectors.toList());
7.skip
作用:获取流中除去前 n 个元素的其它所有元素
List<String> skipNames = names.stream().skip(2).collect(Collectors.toList());
8.map
作用:用于映射每个元素到对应的结果
List<String> mapNames = names.stream().map( str -> "A-"+ str.concat("-A")).collect(Collectors.toList());
List<String> mapStudents = students.stream().map(Student::getName).collect(Collectors.toList());
9.flatMap
作用:流的扁平化处理
flatMap:使用 flatMap 方法的效果是:各个数组并不是分别映射成一个流,而是映射成流的内容 所有使用 map(Arrays::stream) 时生成的单个流被合并起来,即扁平化为一个流
List<Character> flatMap = strings.stream().flatMap(TestStream::getCharacterByString).collect(Collectors.toList());
List<Stream<Character>> map = strings.stream().map(TestStream::getCharacterByString).collect(Collectors.toList());
Stream<Stream<Character>> mapStream = strings.stream().map(TestStream::getCharacterByString);
Stream<Character> flatMapStream = strings.stream().flatMap(TestStream::getCharacterByString);
public static Stream<Character> getCharacterByString(String str) {
List<Character> characterList = new ArrayList<>();
for (Character character : str.toCharArray()) {
characterList.add(character);
}
return characterList.stream();
}
注意: map 和 flatMap 的区别主要体现在返回对象中 map 的返回对象是 Stream<Stream>,而 flatMap 返回的对象是 Stream
10.mapToXxx
作用:转换类型
List<Long> mapToLongStudents = students.stream().mapToLong(Student::getAge).boxed().collect(Collectors.toList());
list.stream().mapToDouble(User::getAge).sum()
list.stream().mapToDouble(User::getAge).max()
list.stream().mapToDouble(User::getAge).min()
list.stream().mapToDouble(User::getAge).average()
11.sorted
作用:用于对流进行排序
List<String> defaultSortedStrings = strings.stream().sorted().collect(Collectors.toList());
List<String> collatorNames = names.stream().sorted(Collator.getInstance(Locale.CHINA)).collect(Collectors.toList());
List<String> reverseOrderNames = names.stream().sorted(Collections.reverseOrder(Collator.getInstance(Locale.CHINA))).collect(Collectors.toList());
List<Student> collectStudents = students.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getId)).collect(Collectors.toList());
12.anyMatch
作用:检查集合中是否至少匹配一个元素,返回 true
boolean anyMatchBcStrings = strings.stream().anyMatch(s -> s.contains("bc"));
13.allMatch
作用:检查是否匹配所有元素,返回 true
boolean result = ints.stream().allMatch(s -> s>0);
14.noneMatch
作用:检查是否没有匹配所有元素,返回 true
boolean result = strings.stream().noneMatch(s -> s.length()<5);
15.findAny
作用:将返回当前流中的任意元素
Optional<String> any = strings.stream().findAny();
any.ifPresent(System.out::println);
Optional<String> any1 = strings.parallelStream().findAny();
any1.ifPresent(System.out::println);
16.findFirst
作用:将返回集合中的第一元素
Optional<String> first = names.stream().findFirst();
first.ifPresent(System.out::println);
17.reduce
作用:可以将流中元素反复结合起来,得到一个值
T reduce(T identity, BinaryOperator<T> accumulator);
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = Arrays.stream(numbers).reduce(0, (a, b) -> a + b);
System.out.println("sum : " + sum);
int sum = Arrays.stream(numbers).reduce(0, Integer::sum);
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = Arrays.stream(numbers).reduce(0, (a, b) -> a + b);
int sum2 = Arrays.stream(numbers).reduce(0, Integer::sum);
int sum3 = Arrays.stream(numbers).reduce(0, (a, b) -> a - b);
int sum4 = Arrays.stream(numbers).reduce(0, (a, b) -> a * b);
int sum5 = Arrays.stream(numbers).reduce(0, (a, b) -> a / b);
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int max = Arrays.stream(numbers).reduce(0, (a, b) -> a > b ? a : b);
int max1 = Arrays.stream(numbers).reduce(0, Integer::max);
int min = Arrays.stream(numbers).reduce(0, (a, b) -> a < b ? a : b);
int min1 = Arrays.stream(numbers).reduce(0, Integer::min);
String[] strings = {"a", "b", "c", "d", "e"};
String reduce = Arrays.stream(strings).reduce("", (a, b) -> a + "|" + b);
String reduce2 = Arrays.stream(strings).reduce("", (a, b) -> {
if (!"".equals(a)) {
return a + "|" + b;
} else {
return b;
}
});
String join = String.join("|", strings);
List<Invoice> invoices = Arrays.asList(
new Invoice("A01", BigDecimal.valueOf(9.99), BigDecimal.valueOf(1)),
new Invoice("A02", BigDecimal.valueOf(19.99), BigDecimal.valueOf(1.5)),
new Invoice("A03", BigDecimal.valueOf(4.99), BigDecimal.valueOf(2))
);
BigDecimal sum = invoices.stream()
.map(x -> x.getQty().multiply(x.getPrice()))
.reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(sum);
System.out.println(sum.setScale(2, RoundingMode.HALF_UP));
class Invoice {
String invoiceNo;
BigDecimal price;
BigDecimal qty;
}
18.count
作用:获取集合中元素的数量
long count = strings.stream().count();
long countStudents = students.stream().filter(student -> (student.getScore() == null ? 0 : student.getScore()) > 90).count();
19.peek
作用:接收一个没有返回值的λ表达式,可以做一些输出,外部处理等
List<Student> peekStudents = students.stream().filter(student -> student.getScore() == null).peek(student -> student.setScore(0)).collect(Collectors.toList());
20.Stream.of
作用:初始化集合
List<String> list = Stream.of("1", "2", "3").collect(Collectors.toList());
21.concat
作用:合并流
Stream<String> s1 = list.stream().filter(s -> s.startsWith("周"));
Stream<String> s2 = Stream.of("Java1", "Java2");
Stream<String> s3 = Stream.concat(s1, s2);
s3.forEach(s -> System.out.println(s));
22.max
Optional<Date> maxDate = list.stream()
.max((p1,p2) -> p1.getDate().compareTo(p2.getDate()))
.map(object -> object.getDate());
Date date = maxDate.get();
Employee oneMax = one.stream().max((o1, o2) -> Double.compare(o1.getBonus() + o1.getSalary(), o2.getSalary() + o2.getBonus())).get();
System.out.println(oneMax);
Topperformer oneTopperformer = one.stream().max((o1, o2) -> Double.compare(o1.getBonus() + o1.getSalary(), o2.getSalary() + o2.getBonus())).map(
employee -> new Topperformer(employee.getName(), employee.getBonus() + employee.getSalary())
).get();
System.out.println(oneTopperformer);
one.stream().sorted((o1, o2) -> Double.compare(o1.getBonus() + o1.getSalary(), o2.getSalary() + o2.getBonus())).
skip(1).limit(one.size()-2).forEach(employee -> {
allMoney += (employee.getBonus() + employee.getSalary());
});
System.out.println("部门1的平均工资为:" + allMoney / (one.size() - 2));
23.分组
Map<String, List<User>> sexAndUserMap = users.parallelStream().collect(Collectors.groupingBy(User::getSex));
Map<String, List<String>> sexAndNameListMap = users.parallelStream().collect(Collectors.groupingBy(User::getSex, Collectors.mapping(User::getName, Collectors.toList())));
Map<String, Set<String>> sexAndNameSetMap = users.parallelStream().collect(Collectors.groupingBy(User::getSex, Collectors.mapping(User::getName, Collectors.toSet())));
Map<String, Map<String, User>> sexAndNameAndDataMap = users.parallelStream().collect(Collectors.groupingBy(User::getSex, Collectors.toMap(User::getName, data -> data)));
Map<String, Map<String, List<User>>> SexAndNameAndUserListMap = users.parallelStream().collect(Collectors.groupingBy(User::getSex, Collectors.groupingBy(User::getName)));
Map<String, String> nameAndSexMap = users.parallelStream().collect(Collectors.toMap(User::getName, User::getSex));
24.orElse 和 orElseGet
- orElse(null)表示如果一个都没找到返回null
- orElseGet(null)表示如果一个都没找到返回null
- 区别就是在使用方法时,即时时没有值 也会执行 orElse 内的方法, 而 orElseGet则不会
@Test
public void test1(){
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
Integer a = list.stream().filter(v->v==2).findFirst().orElse(get("a"));
Integer b = list.stream().filter(v->v==2).findFirst().orElseGet(()->get("b"));
System.out.println("a "+a);
System.out.println("b "+b);
}
public static int get(String name){
System.out.println(name+"执行了方法");
return 1;
}
|