1.reduce
在Java中,可以使用Stream API的reduce方法来计算一个整数列表的乘积。reduce方法是一种累积操作,它可以将流中的元素组合起来,返回单个结果。对于计算乘积,你需要提供一个初始值(通常是1,因为乘法的单位元是1)和一个二元操作符(这里是乘法操作)。
以下是一个示例代码,演示如何使用reduce方法来计算一个整数列表的乘积:
java
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class ProductCalculator {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// 使用reduce方法计算乘积
Optional<Integer> product = numbers.stream()
.reduce(1, (a, b) -> a * b);
// 由于reduce返回的是Optional,需要处理可能的空值
if (product.isPresent()) {
System.out.println("The product of the list is: " + product.get());
} else {
System.out.println("The list is empty or some error occurred.");
}
}
}
``
在这个例子中:
numbers.stream() 创建一个整数列表的流。
.reduce(1, (a, b) -> a * b) 从1开始,将流中的每个元素依次乘以当前的结果。这里1是初始值,(a, b) -> a * b是累积操作(即将当前结果a与下一个元素b相乘)。
reduce方法返回一个Optional<Integer>,因为流操作可能会返回一个空的结果(例如,当流为空时)。
使用if (product.isPresent())来检查乘积是否存在,如果存在则打印乘积,否则打印错误信息。
此外,如果确定列表不会为空,你也可以直接使用orElse方法来提供一个默认值,从而简化代码:
```java
public class ProductCalculator {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// 使用reduce方法计算乘积,并提供默认值
int product = numbers.stream()
.reduce(1, (a, b) -> a * b)
.orElse(1); // 如果列表为空,返回1作为默认值
System.out.println("The product of the list is: " + product);
}
}
在这个改进的版本中,如果流为空,orElse(1)会确保返回一个默认值1,而不是处理Optional对象。
collect和collector.xx
java
List<Student> students = Arrays.asList(
new Student("Alice", 20),
new Student("Bob", 22),
new Student("Charlie", 20),
new Student("David", 22)
);
//Arrays,collections
//按学生的年龄分组。
//
//打印每个年龄对应的学生姓名列表。
students.stream()
.collect(Collectors.groupingBy(Student::getAge))//这里得到一个Map<Integer,list<String>>,然后利用foreach遍历Map集合
.forEach((age, studentsInAge) -> {
System.out.println("Age: " + age);
studentsInAge.forEach(student -> System.out.println(" Name: " + student.getName()));
});
```
### 附:Map集合使用foreach遍历
```java
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});
在 Java 的 Stream
API 中,map
方法用于将流中的每个元素转换为另一种形式。你可以使用 map
方法来对流中的每个元素进行某种操作,并返回一个新的流,其中包含转换后的元素。
stream流的map方法基本用法
map
方法的签名如下:
java
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
T
是流中当前元素的类型。R
是转换后的新元素的类型。Function<T, R>
是一个函数接口,它接受一个T
类型的参数并返回一个R
类型的结果。
示例
- 基本示例:将整数列表中的每个元素平方
java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squares = numbers.stream()
.map(n -> n * n) // 将每个元素平方
.collect(Collectors.toList());
System.out.println(squares); // 输出 [1, 4, 9, 16, 25]
- 将字符串列表中的每个元素转换为大写
java
List<String> words = Arrays.asList("apple", "banana", "grape", "kiwi", "orange");
List<String> upperCaseWords = words.stream()
.map(String::toUpperCase) // 将每个字符串转换为大写
.collect(Collectors.toList());
System.out.println(upperCaseWords); // 输出 [APPLE, BANANA, GRAPE, KIWI, ORANGE]
- 将对象列表中的某个属性提取出来
java
List<Student> students = Arrays.asList(
new Student("Alice", 20),
new Student("Bob", 22),
new Student("Charlie", 20),
new Student("David", 22)
);
List<String> names = students.stream()
.map(Student::getName) // 提取每个学生的姓名
.collect(Collectors.toList());
System.out.println(names); // 输出 [Alice, Bob, Charlie, David]
- 将对象列表中的某个属性转换为另一个对象
java
List<Person> people = Arrays.asList(
new Person("Alice", 20),
new Person("Bob", 17),
new Person("Charlie", 25)
);
List<String> upperCaseNames = people.stream()
.filter(person -> person.getAge() > 18) // 过滤年龄大于18的人
.map(person -> person.getName().toUpperCase()) // 将名字转换为大写
.collect(Collectors.toList());
System.out.println(upperCaseNames); // 输出 [ALICE, CHARLIE]
完整代码示例
以下是你的代码中未完成的部分,以及如何使用 map
方法来完成它:
java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Test01 {
public static void main(String[] args) {
// 其他代码...
System.out.println("-----------------------------------------");
// 过滤出所有年龄大于18岁的人。
// 将他们的名字转换为大写。
// 收集到一个新的列表中并打印。
List<Person> people = Arrays.asList(
new Person("Alice", 20),
new Person("Bob", 17),
new Person("Charlie", 25)
);
List<String> upperCaseNames = people.stream()
.filter(person -> person.getAge() > 18) // 过滤年龄大于18的人
.map(person -> person.getName().toUpperCase()) // 将名字转换为大写
.collect(Collectors.toList()); // 收集到新的列表
System.out.println(upperCaseNames); // 输出 [ALICE, CHARLIE]
}
}
class Person {
String name;
int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
解释
filter(person -> person.getAge() > 18)
:过滤出年龄大于18岁的Person
对象。map(person -> person.getName().toUpperCase())
:将每个Person
对象的名字转换为大写。collect(Collectors.toList())
:将转换后的名字收集到一个新的List
中。
## collector
Collectors
是 Java 8 中 Stream
API 提供的一个强大工具,用于将流中的元素收集到集合或其他数据结构中。以下是一些常见的 Collectors
用法示例:
1. 收集到 List
将流中的元素收集到一个 List
中。
java
List<String> words = Arrays.asList("apple", "banana", "grape", "kiwi", "orange");
List<String> longWords = words.stream()
.filter(word -> word.length() > 5)
.collect(Collectors.toList());
System.out.println(longWords); // 输出 [banana, orange]
2. 收集到 Set
将流中的元素收集到一个 Set
中,自动去重。
java
List<String> words = Arrays.asList("apple", "banana", "apple", "kiwi", "banana");
Set<String> uniqueWords = words.stream()
.collect(Collectors.toSet());
System.out.println(uniqueWords); // 输出 [banana, apple, kiwi]
3. 收集到 Map
将流中的元素收集到一个 Map
中,键为元素本身,值为元素的长度。
java
List<String> words = Arrays.asList("apple", "banana", "grape", "kiwi", "orange");
Map<String, Integer> wordLengthMap = words.stream()
.collect(Collectors.toMap(
word -> word, // Key: 单词本身
String::length // Value: 单词长度
));
System.out.println(wordLengthMap); // 输出 {apple=5, banana=6, grape=5, kiwi=4, orange=6}
4. 分组(Grouping By)
将流中的元素按某个属性分组。
java
List<Student> students = Arrays.asList(
new Student("Alice", 20),
new Student("Bob", 22),
new Student("Charlie", 20),
new Student("David", 22)
);
Map<Integer, List<Student>> studentsByAge = students.stream()
.collect(Collectors.groupingBy(Student::getAge));
studentsByAge.forEach((age, studentList) -> {
System.out.println("Age: " + age);
studentList.forEach(student -> System.out.println(" Name: " + student.getName()));
});
5. 分区(Partitioning By)
将流中的元素按某个条件分为两个分区(true
和 false
)。
java
List<String> words = Arrays.asList("apple", "banana", "grape", "kiwi", "orange");
Map<Boolean, List<String>> partitionedWords = words.stream()
.collect(Collectors.partitioningBy(word -> word.length() > 5));
System.out.println("Long words: " + partitionedWords.get(true)); // 输出 [banana, orange]
System.out.println("Short words: " + partitionedWords.get(false)); // 输出 [apple, grape, kiwi]
6. 连接字符串(Joining)
将流中的字符串元素连接成一个字符串。
java
List<String> words = Arrays.asList("apple", "banana", "grape", "kiwi", "orange");
String joinedWords = words.stream()
.collect(Collectors.joining(", "));
System.out.println(joinedWords); // 输出 apple, banana, grape, kiwi, orange
7. 统计汇总(Summarizing)
对流中的元素进行统计汇总,如求和、平均值、最大值、最小值等。
java
List<Integer> numbers = Arrays.asList(3, 12, 8, 15, 20, 7, 10);
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Sum: " + stats.getSum()); // 输出 75
System.out.println("Average: " + stats.getAverage()); // 输出 10.714285714285714
System.out.println("Max: " + stats.getMax()); // 输出 20
System.out.println("Min: " + stats.getMin()); // 输出 3
8. 自定义收集器
通过 Collector.of
自定义收集器。
java
List<String> words = Arrays.asList("apple", "banana", "grape", "kiwi", "orange");
String concatenated = words.stream()
.collect(Collector.of(
StringBuilder::new, // Supplier: 创建一个新的 StringBuilder
StringBuilder::append, // Accumulator: 将每个元素添加到 StringBuilder
StringBuilder::append, // Combiner: 合并两个 StringBuilder(用于并行流)
StringBuilder::toString // Finisher: 将 StringBuilder 转换为字符串
));
System.out.println(concatenated); // 输出 applebananagrapekiwiorange