JDK1.8 的常用的两个新特性

Lambda表达式实战

List中元素的比较

 List<Integer> list = Arrays.asList(3, 1, 4, 5, 2);
        list.sort((o1,o2)->o1.compareTo(o2));

线程的操作Runnable代码块

  new Thread(()->System.out.println(list));

对集合的遍历

    list.forEach(x->System.out.println(x));
     list.forEach((e)->{
            if(e>=2&&e<5){
                System.out.println("我是大于2小于5的数");
            }else{
                System.out.println("我是其他数");
            }
        });

用lambda表达式实现map

       List<Double> collect = list.stream().map(x -> x + 0.5).collect(Collectors.toList());
        list.stream().map(x->x+0.5).forEach(x->System.out.println(x));

lambda表达式实现map与reduce

例如在本例中,我们将 costBeforeTax 列表的每个元素转换成为税后的值。我们将 x -> x*x lambda表达式传到 map() 方法,后者将其应用到流中的每一个元素。然后用 forEach() 将列表元素打印出来。

使用流API的收集器类,可以得到所有含税的开销。有 toList() 这样的方法将 map 或任何其他操作的结果合并起来。由于收集器在流上做终端操作,因此之后便不能重用流了。你甚至可以用流API的 reduce() 方法将所有数字合成一个,下一个例子将会讲到。
// 不使用lambda表达式为每个订单加上12%的税
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
for (Integer cost : costBeforeTax) {
    double price = cost + .12*cost;
    System.out.println(price);
}
  
// 使用lambda表达式
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
costBeforeTax.stream().map((cost) -> cost + 0.12*cost).forEach(System.out::println);
输出:

112.0
224.0
336.0
448.0
560.0
112.0
224.0
336.0
448.0
560.0
// 为每个订单加上12%的税
// 老方法:
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
double total = 0;
for (Integer cost : costBeforeTax) {
    double price = cost + .12*cost;
    total = total + price;
}
System.out.println("Total : " + total);
 
// 新方法:
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
double bill = costBeforeTax.stream().map((cost) -> cost + .12*cost).reduce((sum, cost) -> sum + cost).get();
System.out.println("Total : " + bill);

输出:

Total : 1680.0
Total : 1680.0

filter操作

 List<Integer> collect1 = list.stream().filter(guid -> !list1.contains(guid)).collect(Collectors.toList());

lambda表达式进行事件处理

// Java 8之前:
JButton show =  ``new` `JButton(``"Show"``);
show.addActionListener(``new` `ActionListener() {
  ``@Override
  ``public` `void` `actionPerformed(ActionEvent e) {
  ``System.out.println(``"Event handling without lambda expression is boring"``);
  ``}
});
// Java 8方式:
show.addActionListener((e) -> {
  ``System.out.println(``"Light, Camera, Action !! Lambda expressions Rocks"``);
});

使用lambda表达式对列表进行迭代

// Java 8之前:
List features = Arrays.asList(``"Lambdas"``, ``"Default Method"``, ``"Stream API"``, ``"Date and Time API"``);
for` `(String feature : features) {
  ``System.out.println(feature);
}
// Java 8之后:
List features = Arrays.asList(``"Lambdas"``, ``"Default Method"``, ``"Stream API"``, ``"Date and Time API"``);
features.forEach(n -> System.out.println(n));
 
// 使用Java 8的方法引用更方便,方法引用由::双冒号操作符标示,
// 看起来像C++的作用域解析运算符
features.forEach(System.out::println);

使用lambda表达式和函数式接口Predicate

public static void main(args[]){
    List languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
 
    System.out.println("Languages which starts with J :");
    filter(languages, (str)->str.startsWith("J"));
 
    System.out.println("Languages which ends with a ");
    filter(languages, (str)->str.endsWith("a"));
 
    System.out.println("Print all languages :");
    filter(languages, (str)->true);
 
    System.out.println("Print no language : ");
    filter(languages, (str)->false);
 
    System.out.println("Print language whose length greater than 4:");
    filter(languages, (str)->str.length() > 4);
}
 
public static void filter(List names, Predicate condition) {
    for(String name: names)  {
        if(condition.test(name)) {
            System.out.println(name + " ");
        }
    }
}

输出:

Languages which starts with J :
Java
Languages which ends with a
Java
Scala
Print all languages :
Java
Scala
C++
Haskell
Lisp
Print no language :
Print language whose length greater than 4:
Scala
Haskell

// 更好的办法
public static void filter(List names, Predicate condition) {
names.stream().filter((name) -> (condition.test(name))).forEach((name) -> {
System.out.println(name + " ");
});
}

如何在lambda表达式中加入Predicate

上个例子说到,java.util.function.Predicate 允许将两个或更多的 Predicate 合成一个。它提供类似于逻辑操作符AND和OR的方法,名字叫做and()、or()和xor(),用于将传入 filter() 方法的条件合并起来。

例如,要得到所有以J开始,长度为四个字母的语言,可以定义两个独立的 Predicate 示例分别表示每一个条件,然后用 Predicate.and() 方法将它们合并起来,如下所示:

// 甚至可以用and()、or()和xor()逻辑函数来合并Predicate,
// 例如要找到所有以J开始,长度为四个字母的名字,你可以合并两个Predicate并传入
Predicate<String> startsWithJ = (n) -> n.startsWith("J");
Predicate<String> fourLetterLong = (n) -> n.length() == 4;
names.stream()
    .filter(startsWithJ.and(fourLetterLong))
    .forEach((n) -> System.out.print("nName, which starts with 'J' and four letter long is : " + n));

类似地,也可以使用 or() 和 xor() 方法。本例着重介绍了如下要点:可按需要将 Predicate 作为单独条件然后将其合并起来使用。简而言之,你可以以传统Java命令方式使用 Predicate 接口,也可以充分利用lambda表达式达到事半功倍的效果。

对列表的每个元素应用函数

我们通常需要对列表的每个元素使用某个函数,例如逐一乘以某个数、除以某个数或者做其它操作。这些操作都很适合用 map() 方法,可以将转换逻辑以lambda表达式的形式放在 map() 方法里,就可以对集合的各个元素进行转换了,如下所示。

// 将字符串换成大写并用逗号链接起来
List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.","Canada");
String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(", "));
System.out.println(G7Countries);

输出:

USA, JAPAN, FRANCE, GERMANY, ITALY, U.K., CANADA

复制不同的值,创建一个子列表

本例展示了如何利用流的 distinct() 方法来对集合进行去重。

复制不同的值,创建一个子列表
本例展示了如何利用流的 distinct() 方法来对集合进行去重。
// 用所有不同的数字创建一个正方形列表
List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
List<Integer> distinct = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
System.out.printf("Original List : %s,  Square Without duplicates : %s %n", numbers, distinct);
输出:

Original List : [9, 10, 3, 4, 7, 3, 4],  Square Without duplicates : [81, 100, 9, 16, 49]

输出:

Original List : [9, 10, 3, 4, 7, 3, 4], Square Without duplicates : [81, 100, 9, 16, 49]

计算集合元素的最大值、最小值、总和以及平均值

IntStream、LongStream 和 DoubleStream 等流的类中,有个非常有用的方法叫做 summaryStatistics() 。可以返回 IntSummaryStatistics、LongSummaryStatistics 或者 DoubleSummaryStatistic s,描述流中元素的各种摘要数据。

在本例中,我们用这个方法来计算列表的最大值和最小值。它也有 getSum() 和 getAverage() 方法来获得列表的所有元素的总和及平均值。

//获取数字的个数、最小值、最大值、总和以及平均值
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("Highest prime number in List : " + stats.getMax());
System.out.println("Lowest prime number in List : " + stats.getMin());
System.out.println("Sum of all prime numbers : " + stats.getSum());
System.out.println("Average of all prime numbers : " + stats.getAverage());

输出:

Highest prime number in List : 29
Lowest prime number in List : 2
Sum of all prime numbers : 129
Average of all prime numbers : 12.9

Collection中的新方法

forEach()
// 使用forEach()结合Lambda表达式迭代
ArrayList<String> list = new ArrayList<>(Arrays.asList("I", "love", "you", "too"));
list.forEach( str -> {
        if(str.length()>3)
            System.out.println(str);
    });
removeIf()
// 使用removeIf()结合Lambda表达式实现
ArrayList<String> list = new ArrayList<>(Arrays.asList("I", "love", "you", "too"));
list.removeIf(str -> str.length()>3); // 删除长度大于3的元素
replaceAll()
需求:假设有一个字符串列表,将其中所有长度大于3的元素转换成大写,其余元素不变。
// 使用Lambda表达式实现
ArrayList<String> list = new ArrayList<>(Arrays.asList("I", "love", "you", "too"));
list.replaceAll(str -> {
    if(str.length()>3)
        return str.toUpperCase();
    return str;
});
sort()
// List.sort()方法结合Lambda表达式
ArrayList<String> list = new ArrayList<>(Arrays.asList("I", "love", "you", "too"));
list.sort((str1, str2) -> str1.length()-str2.length());

stream方法使用

forEach()

我们对forEach()方法并不陌生,在Collection中我们已经见过。方法签名为void forEach(Consumer<? super E> action),作用是对容器中的每个元素执行action指定的动作,也就是对元素进行遍历。

// 使用Stream.forEach()迭代
Stream<String> stream = Stream.of("I", "love", "you", "too");
stream.forEach(str -> System.out.println(str));

由于forEach()是结束方法,上述代码会立即执行,输出所有字符串。

filter()

// 保留长度等于3的字符串
Stream<String> stream= Stream.of("I", "love", "you", "too");
stream.filter(str -> str.length()==3)
    .forEach(str -> System.out.println(str));

distinct()

函数原型为Stream<T> distinct(),作用是返回一个去除重复元素之后的Stream

Stream<String> stream= Stream.of("I", "love", "you", "too", "too");
stream.distinct()
    .forEach(str -> System.out.println(str));

合并

将两个Stream合并为一个Stream可以使用Stream的静态方法concat()

Stream<String> s1 = List.of("A", "B", "C").stream();
Stream<String> s2 = List.of("D", "E").stream();
// 合并:
Stream<String> s = Stream.concat(s1, s2);
System.out.println(s.collect(Collectors.toList())); // [A, B, C, D, E]

分组

Stream<Student> studentStream = Stream.of(
        new Student(1,1,"xiaoming",100),
        new Student(1,2,"xiaozhang",99),
        new Student(2,1,"xiaoming",58),
        new Student(2,3,"xiaoming",68)
        );
Map<Integer, List<Student>> groups = studentStream.collect(Collectors.groupingBy(s -> s.getGradeId(),Collectors.toList()));

输出为Map

stream里面的元素是单个的,map需要key和value,所以我们要在输出的时候把元素映射成key和value存入map

这里我们把元素以:为切割点,前面为key,后面为value

Stream<String> stream = Stream.of("APPL:Apple", "MSFT:Microsoft");
Map<String, String> map = stream
        .collect(Collectors.toMap(
                // 把元素s映射为key:
                s -> s.substring(0, s.indexOf(':')),
                // 把元素s映射为value:
                s -> s.substring(s.indexOf(':') + 1)));

输出到数组

把Stream的元素输出为数组和输出为List类似,我们只需要调用toArray()方法,并传入数组的“构造方法”

List<String> list = List.of("Apple", "Banana", "Orange");
String[] array = list.stream().toArray(String[]::new);

遍历/匹配(foreach/find/match)

public static void main(String[] args) {
List list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);

    // 遍历输出符合条件的元素
    list.stream().filter(x -> x > 6).forEach(System.out::println);
    // 匹配第一个
    Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();
    // 匹配任意(适用于并行流)
    Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();
    // 是否包含符合特定条件的元素
    boolean anyMatch = list.stream().anyMatch(x -> x > 6);
    System.out.println("匹配第一个值:" + findFirst.get());
    System.out.println("匹配任意一个值:" + findAny.get());
    System.out.println("是否存在大于6的值:" + anyMatch);
}
输出:
7
9
8
匹配第一个值:7
匹配任意一个值:8
是否存在大于6的值:true

筛选(filter)

public class StreamTest {
public static void main(String[] args) {
List personList = new ArrayList();
personList.add(new Person(“Tom”, 8900, 23, “male”, “New York”));
personList.add(new Person(“Jack”, 7000, 25, “male”, “Washington”));
personList.add(new Person(“Lily”, 7800, 21, “female”, “Washington”));
personList.add(new Person(“Anni”, 8200, 24, “female”, “New York”));
personList.add(new Person(“Owen”, 9500, 25, “male”, “New York”));
personList.add(new Person(“Alisa”, 7900, 26, “female”, “New York”));

	List<String> fiterList = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName)
			.collect(Collectors.toList());
	System.out.print("薪资高于8000美元的员工:" + fiterList);
}
运行结果:

薪资高于8000美元的员工:[Tom, Anni, Owen]

聚合(max/min/count)

获取员工薪资最高的人。

public class StreamTest {
public static void main(String[] args) {
List personList = new ArrayList();
personList.add(new Person(“Tom”, 8900, 23, “male”, “New York”));
personList.add(new Person(“Jack”, 7000, 25, “male”, “Washington”));
personList.add(new Person(“Lily”, 7800, 21, “female”, “Washington”));
personList.add(new Person(“Anni”, 8200, 24, “female”, “New York”));
personList.add(new Person(“Owen”, 9500, 25, “male”, “New York”));
personList.add(new Person(“Alisa”, 7900, 26, “female”, “New York”));

	Optional<Person> max = personList.stream().max(Comparator.comparingInt(Person::getSalary));
	System.out.println("员工薪资最大值:" + max.get().getSalary());
}

}
输出结果:

员工薪资最大值:9500

计算Integer集合中大于6的元素的个数。

import java.util.Arrays;
import java.util.List;

public class StreamTest {
public static void main(String[] args) {
List list = Arrays.asList(7, 6, 4, 8, 2, 11, 9);

	long count = list.stream().filter(x -> x > 6).count();
	System.out.println("list中大于6的元素个数:" + count);
}

}
输出结果:

list中大于6的元素个数:4

映射(map/flatMap)

将员工的薪资全部增加1000。

public class StreamTest {
public static void main(String[] args) {
List personList = new ArrayList();
personList.add(new Person(“Tom”, 8900, 23, “male”, “New York”));
personList.add(new Person(“Jack”, 7000, 25, “male”, “Washington”));
personList.add(new Person(“Lily”, 7800, 21, “female”, “Washington”));
personList.add(new Person(“Anni”, 8200, 24, “female”, “New York”));
personList.add(new Person(“Owen”, 9500, 25, “male”, “New York”));
personList.add(new Person(“Alisa”, 7900, 26, “female”, “New York”));

	// 不改变原来员工集合的方式
	List<Person> personListNew = personList.stream().map(person -> {
		Person personNew = new Person(person.getName(), 0, 0, null, null);
		personNew.setSalary(person.getSalary() + 10000);
		return personNew;
	}).collect(Collectors.toList());
	System.out.println("一次改动前:" + personList.get(0).getName() + "-->" + personList.get(0).getSalary());
	System.out.println("一次改动后:" + personListNew.get(0).getName() + "-->" + personListNew.get(0).getSalary());

	// 改变原来员工集合的方式
	List<Person> personListNew2 = personList.stream().map(person -> {
		person.setSalary(person.getSalary() + 10000);
		return person;
	}).collect(Collectors.toList());
	System.out.println("二次改动前:" + personList.get(0).getName() + "-->" + personListNew.get(0).getSalary());
	System.out.println("二次改动后:" + personListNew2.get(0).getName() + "-->" + personListNew.get(0).getSalary());
}

}

输出结果:

一次改动前:Tom–>8900
一次改动后:Tom–>18900
二次改动前:Tom–>18900
二次改动后:Tom–>18900

将两个字符数组合并成一个新的字符数组。

public class StreamTest {
public static void main(String[] args) {
List list = Arrays.asList(“m,k,l,a”, “1,3,5,7”);
List listNew = list.stream().flatMap(s -> {
// 将每个元素转换成一个stream
String[] split = s.split(“,”);
Stream s2 = Arrays.stream(split);
return s2;
}).collect(Collectors.toList());

	System.out.println("处理前的集合:" + list);
	System.out.println("处理后的集合:" + listNew);
}

}
输出结果:

处理前的集合:[m-k-l-a, 1-3-5]
处理后的集合:[m, k, l, a, 1, 3, 5]

map系列还有mapToInt、mapToLong、mapToDouble三个函数,它们以一个映射函数为入参,将流中每一个元素处理后生成一个新流。以mapToInt为例,看两个示例:

public static void main(String[] args) {
// 输出字符串集合中每个字符串的长度
List stringList = Arrays.asList(“mu”, “CSDN”, “hello”,
“world”, “quickly”);
stringList.stream().mapToInt(String::length).forEach(System.out::println);
// 将int集合的每个元素增加1000
List integerList = Arrays.asList(4, 5, 2, 1, 6, 3);
integerList.stream().mapToInt(x -> x + 1000).forEach(System.out::println);
}

mapToInt三个函数生成的新流,可以进行很多后续操作,比如求最大最小值、求和、求平均值:

public static void main(String[] args) {
List doubleList = Arrays.asList(1.0, 2.0, 3.0, 4.0, 2.0);
double average = doubleList.stream().mapToDouble(Number::doubleValue).average().getAsDouble();
double sum = doubleList.stream().mapToDouble(Number::doubleValue).sum();
double max = doubleList.stream().mapToDouble(Number::doubleValue).max().getAsDouble();
System.out.println(“平均值:” + average + “,总和:” + sum + “,最大值:” + max);
}

归约(reduce)

求Integer集合的元素之和、乘积和最大值。

public class StreamTest {
public static void main(String[] args) {
List list = Arrays.asList(1, 3, 2, 8, 11, 4);
// 求和方式1
Optional sum = list.stream().reduce((x, y) -> x + y);
// 求和方式2
Optional sum2 = list.stream().reduce(Integer::sum);
// 求和方式3
Integer sum3 = list.stream().reduce(0, Integer::sum);

	// 求乘积
	Optional<Integer> product = list.stream().reduce((x, y) -> x * y);

	// 求最大值方式1
	Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
	// 求最大值写法2
	Integer max2 = list.stream().reduce(1, Integer::max);

	System.out.println("list求和:" + sum.get() + "," + sum2.get() + "," + sum3);
	System.out.println("list求积:" + product.get());
	System.out.println("list求最大值:" + max.get() + "," + max2);
}

}
输出结果:

list求和:29,29,29
list求积:2112
list求最大值:11,11

求所有员工的工资之和和最高工资。

public class StreamTest {
public static void main(String[] args) {
List personList = new ArrayList();
personList.add(new Person(“Tom”, 8900, 23, “male”, “New York”));
personList.add(new Person(“Jack”, 7000, 25, “male”, “Washington”));
personList.add(new Person(“Lily”, 7800, 21, “female”, “Washington”));
personList.add(new Person(“Anni”, 8200, 24, “female”, “New York”));
personList.add(new Person(“Owen”, 9500, 25, “male”, “New York”));
personList.add(new Person(“Alisa”, 7900, 26, “female”, “New York”));

	// 求工资之和方式1:
	Optional<Integer> sumSalary = personList.stream().map(Person::getSalary).reduce(Integer::sum);
	// 求工资之和方式2:
	Integer sumSalary2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(),
			(sum1, sum2) -> sum1 + sum2);
	// 求工资之和方式3:
	Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);

	// 求最高工资方式1:
	Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
			Integer::max);
	// 求最高工资方式2:
	Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
			(max1, max2) -> max1 > max2 ? max1 : max2);
	// 求最高工资方式3:
	Integer maxSalary3 = personList.stream().map(Person::getSalary).reduce(Integer::max).get();

	System.out.println("工资之和:" + sumSalary.get() + "," + sumSalary2 + "," + sumSalary3);
	System.out.println("最高工资:" + maxSalary + "," + maxSalary2 + "," + maxSalary3);
}

}
输出结果:

工资之和:49300,49300,49300
最高工资:9500,9500

Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。

public class StreamTest {

​ public static void main(String[] args) {
​ List personList = new ArrayList();
​ personList.add(new Person(“Tom”, 8900, 23, “male”, “New York”));
​ personList.add(new Person(“Jack”, 7000, 25, “male”, “Washington”));
​ personList.add(new Person(“Lily”, 7800, 21, “female”, “Washington”));

	// 每个员工减去起征点后的薪资之和(这个例子并不严谨,但一时没想到好的例子)
	Integer sum = personList.stream().collect(Collectors.reducing(0, Person::getSalary, (i, j) -> (i + j - 5000)));
	System.out.println("员工扣税薪资总和:" + sum);

	// stream的reduce
	Optional<Integer> sum2 = personList.stream().map(Person::getSalary).reduce(Integer::sum);
	System.out.println("员工薪资总和:" + sum2.get());
}

}
运行结果:

员工扣税薪资总和:8700
员工薪资总和:23700

归集(toList/toSet/toMap)

因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。toList、toSet和toMap比较常用,另外还有toCollection、toConcurrentMap等复杂一些的用法。

下面用一个案例演示toList、toSet和toMap:

public class StreamTest {
public static void main(String[] args) {
List list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
List listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
Set set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());

	List<Person> personList = new ArrayList<Person>();
	personList.add(new Person("Tom", 8900, 23, "male", "New York"));
	personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
	personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
	personList.add(new Person("Anni", 8200, 24, "female", "New York"));
	
	Map<?, Person> map = personList.stream().filter(p -> p.getSalary() > 8000)
			.collect(Collectors.toMap(Person::getName, p -> p));
	System.out.println("toList:" + listNew);
	System.out.println("toSet:" + set);
	System.out.println("toMap:" + map);
}

}
运行结果:

toList:[6, 4, 6, 6, 20]
toSet:[4, 20, 6]
toMap:{Tom=mutest.Person@5fd0d5ae, Anni=mutest.Person@2d98a335}

统计(count/averaging)

Collectors提供了一系列用于数据统计的静态方法:

计数:count
平均值:averagingInt、averagingLong、averagingDouble
最值:maxBy、minBy
求和:summingInt、summingLong、summingDouble
统计以上所有:summarizingInt、summarizingLong、summarizingDouble

案例:统计员工人数、平均工资、工资总额、最高工资。

public class StreamTest {
public static void main(String[] args) {
List personList = new ArrayList();
personList.add(new Person(“Tom”, 8900, 23, “male”, “New York”));
personList.add(new Person(“Jack”, 7000, 25, “male”, “Washington”));
personList.add(new Person(“Lily”, 7800, 21, “female”, “Washington”));

	// 求总数
	Long count = personList.stream().collect(Collectors.counting());
	// 求平均工资
	Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
	// 求最高工资
	Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
	// 求工资之和
	Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
	// 一次性统计所有信息
	DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));

	System.out.println("员工总数:" + count);
	System.out.println("员工平均工资:" + average);
	System.out.println("员工工资总和:" + sum);
	System.out.println("员工工资所有统计:" + collect);
}

}
运行结果:

员工总数:3
员工平均工资:7900.0
员工工资总和:23700
员工工资所有统计:DoubleSummaryStatistics{count=3, sum=23700.000000,min=7000.000000, average=7900.000000, max=8900.000000}

分组(partitioningBy/groupingBy)

分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。

案例:将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组

public class StreamTest {
public static void main(String[] args) {
List personList = new ArrayList();
personList.add(new Person(“Tom”, 8900, “male”, “New York”));
personList.add(new Person(“Jack”, 7000, “male”, “Washington”));
personList.add(new Person(“Lily”, 7800, “female”, “Washington”));
personList.add(new Person(“Anni”, 8200, “female”, “New York”));
personList.add(new Person(“Owen”, 9500, “male”, “New York”));
personList.add(new Person(“Alisa”, 7900, “female”, “New York”));

	// 将员工按薪资是否高于8000分组
    Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
    // 将员工按性别分组
    Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));
    // 将员工先按性别分组,再按地区分组
    Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
    System.out.println("员工按薪资是否大于8000分组情况:" + part);
    System.out.println("员工按性别分组情况:" + group);
    System.out.println("员工按性别、地区:" + group2);
}

}
输出结果:

员工按薪资是否大于8000分组情况:{false=[mutest.Person@2d98a335, mutest.Person@16b98e56, mutest.Person@7ef20235], true=[mutest.Person@27d6c5e0, mutest.Person@4f3f5b24, mutest.Person@15aeb7ab]}
员工按性别分组情况:{female=[mutest.Person@16b98e56, mutest.Person@4f3f5b24, mutest.Person@7ef20235], male=[mutest.Person@27d6c5e0, mutest.Person@2d98a335, mutest.Person@15aeb7ab]}
员工按性别、地区:{female={New York=[mutest.Person@4f3f5b24, mutest.Person@7ef20235], Washington=[mutest.Perso

接合(joining)

joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。

public class StreamTest {
public static void main(String[] args) {
List personList = new ArrayList();
personList.add(new Person(“Tom”, 8900, 23, “male”, “New York”));
personList.add(new Person(“Jack”, 7000, 25, “male”, “Washington”));
personList.add(new Person(“Lily”, 7800, 21, “female”, “Washington”));

	String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));
	System.out.println("所有员工的姓名:" + names);
	List<String> list = Arrays.asList("A", "B", "C");
	String string = list.stream().collect(Collectors.joining("-"));
	System.out.println("拼接后的字符串:" + string);
}

}
运行结果:

所有员工的姓名:Tom,Jack,Lily
拼接后的字符串:A-B-C

提取/组合
流也可以进行合并、去重、限制、跳过等操作。

public class StreamTest {
public static void main(String[] args) {
String[] arr1 = { “a”, “b”, “c”, “d” };
String[] arr2 = { “d”, “e”, “f”, “g” };

	Stream<String> stream1 = Stream.of(arr1);
	Stream<String> stream2 = Stream.of(arr2);
	// concat:合并两个流 distinct:去重
	List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
	// limit:限制从流中获得前n个数据
	List<Integer> collect = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
	// skip:跳过前n个数据
	List<Integer> collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());

	System.out.println("流合并:" + newList);
	System.out.println("limit:" + collect);
	System.out.println("skip:" + collect2);
}

}
运行结果:

流合并:[a, b, c, d, e, f, g]
limit:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
skip:[3, 5, 7, 9, 11]

排序(sorted)

sorted,中间操作。有两种排序:

sorted():自然排序,流中元素需实现Comparable接口
sorted(Comparator com):Comparator排序器自定义排序
案例:将员工按工资由高到低(工资一样则按年龄由大到小)排序

public class StreamTest {
public static void main(String[] args) {
List personList = new ArrayList();

	personList.add(new Person("Sherry", 9000, 24, "female", "New York"));
	personList.add(new Person("Tom", 8900, 22, "male", "Washington"));
	personList.add(new Person("Jack", 9000, 25, "male", "Washington"));
	personList.add(new Person("Lily", 8800, 26, "male", "New York"));
	personList.add(new Person("Alisa", 9000, 26, "female", "New York"));

	// 按工资升序排序(自然排序)
	List<String> newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)
			.collect(Collectors.toList());
	// 按工资倒序排序
	List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
			.map(Person::getName).collect(Collectors.toList());
	// 先按工资再按年龄升序排序
	List<String> newList3 = personList.stream()
			.sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName)
			.collect(Collectors.toList());
	// 先按工资再按年龄自定义排序(降序)
	List<String> newList4 = personList.stream().sorted((p1, p2) -> {
		if (p1.getSalary() == p2.getSalary()) {
			return p2.getAge() - p1.getAge();
		} else {
			return p2.getSalary() - p1.getSalary();
		}
	}).map(Person::getName).collect(Collectors.toList());

	System.out.println("按工资升序排序:" + newList);
	System.out.println("按工资降序排序:" + newList2);
	System.out.println("先按工资再按年龄升序排序:" + newList3);
	System.out.println("先按工资再按年龄自定义降序排序:" + newList4);
}

}
运行结果:

按工资升序排序:[Lily, Tom, Sherry, Jack, Alisa]
按工资降序排序:[Sherry, Jack, Alisa, Tom, Lily]
先按工资再按年龄升序排序:[Lily, Tom, Sherry, Jack, Alisa]
先按工资再按年龄自定义降序排序:[Alisa, Jack, Sherry, Tom, Lily]

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋斗的老史

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值