Java基础学习day08-作业
案例一
// 1. Runnable 接口 Runnable runnable = new Runnable() { public void run() { System.out.println("Hello World"); } }; // 2. Comparator 接口 Comparator<String> comparator = new Comparator<String>() { public int compare(String s1, String s2) { return s1.length() - s2.length(); } };
package com.itheima.homework_day08; import java.util.Comparator; public class Test1 { public static void main(String[] args) { // 1. Runnable 接口 Runnable runnable = () -> System.out.println("Hello World"); // 2. Comparator 接口 Comparator<String> comparator = (s1, s2) -> s1.length() - s2.length(); } }
案例二
题目2:自定义函数式接口 创建一个自定义函数式接口NumberProcessor,并使用Lambda实现: 定义接口:int process(int x, int y) 创建方法接收该接口和两个整数参数 使用Lambda实现加法、乘法和取最大值操作
package com.itheima.homework_day08; public interface NumberProcessor { int process(int x, int y); }
package com.itheima.homework_day08; public class Test2 { public static int calculate(int x, int y, NumberProcessor numberProcessor) { return numberProcessor.process(x, y); } public static void main(String[] args) { //题目2:自定义函数式接口 //创建一个自定义函数式接口NumberProcessor,并使用Lambda实现: // //定义接口:int process(int x, int y) // //创建方法接收该接口和两个整数参数 // //使用Lambda实现加法、乘法和取最大值操作 int calculate = calculate(2, 3, (int x, int y) -> x + y); } }
案例三
题目3:整数数组处理 题目: 有一个整数数组:int[] numbers = {10, 20, 30, 40, 50}; 请使用 Lambda 表达式完成以下操作: 打印所有数字 打印数字的平方 打印数字是否是偶数
// 定义函数式接口用于整数处理 interface IntProcessor { void process(int number, int index); // 添加index参数 }
public class Main { // 整数数组遍历方法(使用普通for循环) public static void forEachInt(int[] array, IntProcessor processor) { for (int i = 0; i < array.length; i++) { processor.process(array[i], i); // 传递数字和索引 } } public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; // 1. 打印所有数字(带索引) System.out.println("所有数字(带索引):"); forEachInt(numbers, (n, index) -> { System.out.println("索引 " + index + ": 数字 = " + n); }); // 2. 打印数字的平方(带索引) System.out.println("\n数字的平方:"); forEachInt(numbers, (n, index) -> { int square = n * n; System.out.println("索引 " + index + ": " + n + " 的平方 = " + square); }); // 3. 打印数字是否是偶数(带索引) System.out.println("\n数字奇偶性:"); forEachInt(numbers, (n, index) -> { boolean isEven = n % 2 == 0; System.out.println("索引 " + index + ": " + n + " 是" + (isEven ? "偶数" : "奇数")); }); } }