### Java——集合框架的深邃海洋(续)
在我们的Java集合框架探索之旅中,我们已经涉足了基本操作、高级特性,现在让我们深入探讨一些特定场景下的应用和进阶技巧,比如集合的分区操作、分组、并行流的性能考量,以及如何利用`Collectors`进行复杂数据聚合,这些将为您的编程实践增添更多维度。
#### 集合分区
`Collectors.partitioningBy`方法可以根据条件将集合分为两个部分,这对于数据分析和条件筛选非常有用。```java
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class PartitioningExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eva");
Map<Boolean, List<String>> partitioned = names.stream()
.collect(Collectors.partitioningBy(name -> name.length() > 5));
System.out.println("Short names: " + partitioned.get(false));
System.out.println("Long names: " + partitioned.get(true));
}
}
```
#### 分组操作
`groupingBy`允许根据某些特征对集合进行分组。```java
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class GroupingByExample {
public static void main(String[] args) {
Person[] people = {
new Person("Alice", "Engineer"),
new Person("Bob", "Artist"),
new Person("Charlie", "Engineer"),
new Person("David", "Doctor")
};
Map<String, List<Person>> byProfession = Arrays.stream(people)
.collect(Collectors.groupingBy(Person::getProfession));
byProfession.forEach((profession, group) ->
System.out.println(profession + ": " + group.stream().map(Person::getName).collect(Collectors.toList())));
}
}
static class Person {
private String name;
private String profession;
Person(String name, String profession) {
this.name = name;
this.profession = profession;
}
public String getName() { return name; }
public String getProfession() { return profession; }
}
}
```
#### 并行流性能考量
虽然并行流可以提高性能,但并非总是最佳选择,特别是对于小数据集或操作成本较低的任务。了解何时使用很重要。```java
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.LongStream;
public class ParallelStreamPerformance {
public static void main(String[] args) {
long startTime;
long endTime;
startTime = System.nanoTime();
long sum = LongStream.rangeClosed(1, 1_000_000_000L).sum();
endTime = System.nanoTime();
System.out.println("Sequential sum: " + sum + ", TimeUnit.NANOSECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS));
startTime = System.nanoTime();
sum = LongStream.rangeClosed(1, 1_000_000_000L).parallel().sum();
endTime = System.nanoTime();
System.out.println("Parallel sum: " + sum + ", TimeUnit.NANOSECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS));
}
}
```
#### Collectors的高级用法
`Collectors.joining`、`toMap`等提供了强大的数据聚合能力。```java
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class AdvancedCollectorsExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("Hello", "World", "Java", "Programming");
String sentence = words.stream().collect(Collectors.joining(" "));
System.out.println(sentence); // Hello World Java Programming
Map<Character, Long> charCount = words.stream()
.flatMapToInt(String::chars)
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println(charCount);
}
}
```
通过这些追加的实践和示例,我们不仅掌握了集合框架在更具体场景下的应用,还学会了如何评估并行流的性能,以及如何巧妙地利用`Collectors`进行复杂的数据转换和聚合,进一步扩展了Java集合框架的使用深度和广度。