Java Stream API:面试问题每个开发人员都应练习
2025-02-07 16:43:01
为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对象数组,按年龄升级排序,同龄按姓名升级排序
立即学习“Java免费学习笔记(深入);
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(aray1), 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确保按键排序。
- 使用Colectors使用collectors.toList()在同一键下存储多个员工。
- 重复处理:如果多个员工有相同的id,则将其存储在键下的列表中。
希望这些问题和答案能帮助你在Java Stream 在API面试中取得好成绩! 记住,理解背后的逻辑比只记住代码更重要。 多练习,多思考,才能真正掌握Stream API的精髓。
以上是Java Stream API:每个开发人员都应该练习面试问题的详细内容。请关注图灵教育的其他相关文章!
