Java8新特性 - Lambda表达式 - Functional Interfaces

本文展示了如何使用Java 8的Lambda表达式实现映射操作,包括将字符串数组映射到长度数组,以及将整数数组映射到平方数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mapper.java

package corejava8.lambda;

@FunctionalInterface
public interface Mapper<T> {
// An abstract method
int map(T source);

// A generic static method
public static <U> int[] mapToInt(U[] list, Mapper<? super U> mapper) {
int[] mappedValues = new int[list.length];
for (int i = 0; i < list.length; i++) {
// Map the object to an int
mappedValues[i] = mapper.map(list[i]);
}
return mappedValues;
}
}


MapperTest.java

package corejava8.lambda;

public class MapperTest {
public static void main(String[] args) {
// Map names using their length
System.out.println("Mapping names to their lengths:");
String[] names = { "David", "Li", "Doug" };
int[] lengthMapping = Mapper.mapToInt(names,
(String name) -> name.length());
printMapping(names, lengthMapping);
System.out.println("\nMapping integers to their squares:");
Integer[] numbers = { 7, 3, 67 };
int[] countMapping = Mapper.mapToInt(numbers, (Integer n) -> n * n);
printMapping(numbers, countMapping);
}

public static void printMapping(Object[] from, int[] to) {
for (int i = 0; i < from.length; i++) {
System.out.println(from[i] + " mapped to " + to[i]);
}
}
}


运行结果:
Mapping names to their lengths:
David mapped to 5
Li mapped to 2
Doug mapped to 4

Mapping integers to their squares:
7 mapped to 49
3 mapped to 9
67 mapped to 4489
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值