面试题答案
一键面试功能不同
count()
方法:用于统计流中元素的数量。它只关心元素的个数,不涉及对元素本身的处理和转换。collect()
方法:用于将流中的元素收集到特定的容器(如List
、Set
、Map
等)中,或者对元素进行复杂的归约操作。它更侧重于对元素进行收集和变换。
适用场景不同
count()
方法:当只需要知道流中元素的数量时,使用count()
方法,例如统计数据库查询结果的行数。collect()
方法:当需要将流中的元素收集到特定的数据结构(如List
、Set
等),或者对元素进行分组、汇总等复杂操作时,使用collect()
方法。比如将数据库查询结果按某个字段分组,或者将查询结果收集到List
中进行后续处理。
返回值类型不同
count()
方法:返回值类型是long
,表示流中元素的数量。collect()
方法:返回值类型取决于收集器(Collector
),可以是List
、Set
、Map
等各种类型。例如使用Collectors.toList()
收集器返回List
,使用Collectors.toSet()
收集器返回Set
。
示例:使用collect()
方法进行元素收集并转换为特定的数据结构
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class StreamCollectExample {
public static void main(String[] args) {
// 原始数组
Integer[] numbers = {1, 2, 3, 4, 5};
// 收集到List
List<Integer> numberList = Arrays.stream(numbers)
.collect(Collectors.toList());
System.out.println("收集到List: " + numberList);
// 收集到Set
Set<Integer> numberSet = Arrays.stream(numbers)
.collect(Collectors.toSet());
System.out.println("收集到Set: " + numberSet);
}
}
上述代码通过Arrays.stream(numbers)
将数组转换为流,然后分别使用Collectors.toList()
和Collectors.toSet()
收集器将流中的元素收集到List
和Set
中。