Stream练习
拼接
给定一个字符串数组,使用 Stream 把所有字符串拼接成一个字符串。
String[] arr = {"a", "b", "c"};
输出: abc
public class ConcatTest {
//给定一个字符串数组,使用 Stream 把所有字符串拼接成一个字符串。
public static void main(String[] args) {
String[] arr = {"a","b","c"};
System.out.println(concat(arr));
}
public static String concat(String[] arr){
Stream<String> stream = Arrays.stream(arr);
return stream.reduce("",(s, s2) -> s + s2);
}
}
求值
有一个整数集合,分别完成以下操作:
- 所有元素之和
- 最大值
- 最小值
public class IntStream {
/*有一个整数集合,分别完成以下操作:
- 所有元素之和
- 最大值
- 最小值
*/
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(2, 8, 5, 3, 9, 1, 6, 4, 7);
System.out.println("和是" + sum( integerList));
System.out.println("最小值是" + min( integerList));
System.out.println("最大值是" + max( integerList));
}
public static int sum(List integerList){
Stream<Integer> stream = integerList.stream();
Integer sum = stream.reduce(0, (a, b) -> a + b);
return sum;
}
public static int min(List integerList){
Stream<Integer> stream = integerList.stream();
Integer min = stream.min((a, b) -> a - b).get();
return min;
}
public static int max(List integerList){
Stream<Integer> stream = integerList.stream();
Integer max = stream.max((a, b) -> (a - b)).get();
return max;
}
}
薪资最低的员工
有一个员工类Employee,里面有name、age和salary字段。请通过 Stream 对多个Employee对象按salary排序,然后取前3个输出。
public class MinimumSarlay {
public static void main(String[] args) {
//有一个员工类Employee,里面有name、age和salary字段。请通过 Stream 对多个Employee对象按salary排序,然后取前3个输出。
Employee e1 = new Employee("美琪",18,7890.9);
Employee e2 = new Employee("美雪",18,9865.5);
Employee e3 = new Employee("小蓝",21,5875.9);
Employee e4 = new Employee("小月",23,6743.2);
Employee e5 = new Employee("严莉莉",25,12345.9);
Employee[] employees= {e1,e2,e3,e4,e5};
sort(employees);
}
public static void sort(Employee[] employees) {
Stream<Employee> stream = Arrays.stream(employees);
Stream<Employee> sorted = stream
.sorted(Comparator.comparingDouble(Employee::getSalary))
.limit(2);
sorted.forEach(System.out::println);
}
}
平均值
有一个整数集合,求每个元素平方的平均值。
public class Average {
//有一个整数集合,求每个元素平方的平均值。
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(2, 8, 5, 3, 9, 1, 6, 4, 7);
average(integerList);
}
public static void average(List integerList){
Stream<Integer> stream = integerList.stream();
//OptionalDouble处理空集合情况
OptionalDouble average = stream
.mapToDouble(num -> Math.pow(num, 2))
.average();
System.out.println("每个元素平方的平均值是:" + average);
}
}