Java Stream API:面试问题每个开发人员都应练习
时间:2025-02-02 11:28:02 291浏览 收藏
从现在开始,努力学习吧!本文《Java Stream API:面试问题每个开发人员都应练习》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!
准备Java开发人员面试?Stream API是面试中常见的考点,它以优雅的方式处理数据集合而闻名。本文将带您了解15道真实的Stream API面试题,助您掌握Java Stream。
问题1:在数组中查找最大元素
int arr[] = {5,1,2,8};
int max = Arrays.stream(arr).max().getAsInt();
问题2:打印字符串中每个字符的计数
String str = "now is the winter";
Map<String, Long> charFreq = Arrays.stream(str.split(""))
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
问题3:合并两个Person对象数组,按年龄升序排序,年龄相同则按姓名升序排序
class Person {
String name;
int age;
// constructors and getters
}
Person[] plist1 = {new Person("alice", 25), new Person("bob", 30), new Person("charlie", 25)};
Person[] plist2 = {new Person("david", 30), new Person("eve", 25), new Person("alice", 25)};
Stream.concat(Arrays.stream(plist1), Arrays.stream(plist2))
.sorted(Comparator.comparingInt(Person::getAge)
.thenComparing(Person::getName))
.forEach(System.out::println);
问题4:查找字符串列表中最长字符串的长度
List<String> names = Arrays.asList("alice", "bob", "charlie", "david", "eva");
int maxLength = names.stream()
.mapToInt(String::length)
.max()
.orElse(0);
问题5:检查整数列表是否包含素数
List<Integer> numbers = Arrays.asList(4, 6, 8, 11, 12, 13, 14, 15);
boolean hasPrime = numbers.stream()
.anyMatch(num -> isPrime(num));
private static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= Math.sqrt(num); i++)
if (num % i == 0) return false;
return true;
}
问题6:计算多个句子中不同单词(不区分大小写)的总数
List<String> sentences = Arrays.asList(
"Java Stream API provides a fluent interface",
"It supports functional-style operations on streams",
"In this exercise, you need to count words"
);
long uniqueWords = sentences.stream()
.map(x -> x.toLowerCase().split(" "))
.flatMap(Arrays::stream)
.distinct()
.count();
问题7:查找并连接前两个长度为偶数的单词
List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");
String result = words.stream()
.filter(x -> x.length() % 2 == 0)
.limit(2)
.collect(Collectors.joining(""));
问题8:给定交易列表,查找每天的交易总额,并按日期排序
class Transaction {
String date;
long amount;
// constructors and getters
}
List<Transaction> transactions = Arrays.asList(
new Transaction("2022-01-01", 100),
new Transaction("2022-01-01", 200),
new Transaction("2022-01-02", 300)
);
Map<String, Long> dailyTotals = transactions.stream()
.collect(Collectors.groupingBy(
Transaction::getDate,
TreeMap::new, // Use TreeMap for sorted order
Collectors.summingLong(Transaction::getAmount)
));
问题9:合并两个整数数组,排序,并过滤掉大于指定阈值的数字
int[] array1 = {1, 5, 3, 9, 7};
int[] array2 = {2, 4, 6, 8, 10};
int threshold = 7;
IntStream.concat(Arrays.stream(array1), Arrays.stream(array2))
.boxed()
.sorted(Comparator.naturalOrder())
.filter(x -> x <= threshold) // Corrected filter condition
.forEach(System.out::println);
问题10:将员工记录列表转换为部门到平均工资的地图
class Employee {
String department;
double salary;
// constructor and getters
}
Map<String, Double> deptAvgSalary = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.averagingDouble(Employee::getSalary)
));
问题11:将数字列表分成两组:素数和非素数
List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9, 10);
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(num -> isPrime(num)));
问题12:使用Stream生成斐波那契数列,最多n项
Stream.iterate(new int[]{0, 1},
arr -> new int[]{arr[1], arr[0] + arr[1]})
.limit(10)
.map(arr -> arr[0])
.forEach(System.out::println);
问题13:按首字母分组字符串,并计算每个组的出现次数
List<String> words = Arrays.asList("apple", "banana", "bear", "cat", "apple");
Map<Character, Long> frequency = words.stream()
.collect(Collectors.groupingBy(
str -> str.charAt(0),
Collectors.counting()
));
// output: {a=2, b=2, c=1}
问题14:使用Java Stream查找两个列表的交集
List<Integer> list3 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list4 = Arrays.asList(3, 4, 5, 6, 7);
List<Integer> intersection =
list3.stream().filter(list4::contains).toList();
System.out.println(intersection);
问题15:在Java中处理重复键时,如何将对象列表转换为排序的地图?
class Employee {
int id;
String name;
// constructor and getters
}
List<Employee> employees = Arrays.asList(
new Employee(101, "Alice"),
new Employee(102, "Bob"),
new Employee(101, "Charlie"),
new Employee(103, "David"),
new Employee(102, "Eve")
);
Map<Integer, List<Employee>> employeeMap = employees.stream()
.collect(Collectors.groupingBy(
Employee::getId,
TreeMap::new,
Collectors.toList()
));
解释:
Collectors.groupingBy(Employee::getId, TreeMap::new, Collectors.toList())
:
- 按
id
分组(键)。 - 使用
TreeMap
确保按键排序。 - 使用
Collectors.toList()
将多个员工存储在同一键下。 - 处理重复:如果多个员工具有相同的
id
,则将其存储在该键下的列表中。
希望这些题目和解答能帮助您在Java Stream API面试中取得好成绩! 记住,理解背后的逻辑比仅仅记住代码更重要。 多练习,多思考,才能真正掌握Stream API的精髓。
到这里,我们也就讲完了《Java Stream API:面试问题每个开发人员都应练习》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
364 收藏
-
478 收藏
-
464 收藏
-
347 收藏
-
468 收藏
-
200 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 507次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习