Java mapToInt()方法使用小结
作者:Geoking.
本文介绍了Java 8中Stream API中的mapToInt()方法,它可以将对象流转换为整型流,从而方便地进行求和、求平均值、求最大值/最小值等操作,具有一定的参考价值,感兴趣的可以了解一下
一、用途
在 Java 8 引入 Stream API 之后,集合处理变得更函数式、更简洁。
在处理对象集合时经常需要把对象中的某个字段(年龄、数量、价格等)提取成整型流(IntStream),以便:
- 快速求和(
sum()) - 求平均值(
average()) - 求最大值/最小值(
max()/min()) - 转换为基本类型数组(
toArray())
要完成这些操作,最常用的方法之一就是 —— mapToInt()。
二、什么是mapToInt()?
mapToInt() 是 Stream 接口中的一个终极武器,它可以将 Stream 转换为 IntStream。
方法签名如下:
IntStream mapToInt(ToIntFunction<? super T> mapper);
功能总结:
将对象流中的元素映射为 int 类型,返回 IntStream。
三、mapToInt()有什么用?
1. 将对象集合转换为整型流
例如:把 List<Person> 中的年龄转换为 IntStream。
2. 使用 IntStream 的快速计算
例如:
.sum().average().max().min().toArray()
这些是普通 Stream 没有的强大方法。
3. 避免自动装箱 / 拆箱,提高性能
IntStream 是基础类型流,不涉及 Integer 的装箱操作,性能更高。
四、基本用法示例
示例:提取对象字段为整型流
class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
}
public class Demo {
public static void main(String[] args) {
List<Person> people = List.of(
new Person("Tom", 18),
new Person("Jerry", 20),
new Person("Alice", 22)
);
IntStream ages = people.stream()
.mapToInt(Person::getAge);
ages.forEach(System.out::println);
}
}
输出:
18
20
22
五、典型应用场景
1. 求和:sum()
int totalAge = people.stream()
.mapToInt(Person::getAge)
.sum();
System.out.println(totalAge); // 60
2. 求平均值:average()
double avgAge = people.stream()
.mapToInt(Person::getAge)
.average()
.orElse(0);
System.out.println(avgAge); // 20.0
3. 求最大值 / 最小值
int maxAge = people.stream()
.mapToInt(Person::getAge)
.max()
.orElse(-1);
int minAge = people.stream()
.mapToInt(Person::getAge)
.min()
.orElse(-1);
System.out.println(maxAge); // 22
System.out.println(minAge); // 18
4. 转为int[]
int[] arr = people.stream()
.mapToInt(Person::getAge)
.toArray();
System.out.println(Arrays.toString(arr));
// 输出: [18, 20, 22]
六、使用 Lambda 表达式
除了方法引用,也可以使用 Lambda:
int total = people.stream()
.mapToInt(p -> p.getAge())
.sum();
但一般用方法引用更方便,这是 Java 8 引入的方法引用(Method Reference),它是一种简化 Lambda 表达式的语法形式。
七、与map()的区别
| 方法 | 返回类型 | 用途 |
|---|---|---|
| map() | Stream<R> | 返回对象流 |
| mapToInt() | IntStream | 返回整型流,适合数学计算 |
示例:
Stream<Integer> stream1 = people.stream()
.map(Person::getAge); // 装箱 Integer,不适合大量计算
IntStream stream2 = people.stream()
.mapToInt(Person::getAge); // 基本类型 int 流,高性能
八、实战案例:计算商品总价格
class Item {
private String name;
private int price;
Item(String name, int price) {
this.name = name;
this.price = price;
}
public int getPrice() {
return price;
}
}
public class Demo {
public static void main(String[] args) {
List<Item> items = List.of(
new Item("Book", 30),
new Item("Pen", 5),
new Item("Bag", 60)
);
int totalPrice = items.stream()
.mapToInt(Item::getPrice)
.sum();
System.out.println("总价格:" + totalPrice);
}
}
输出:
总价格:95
到此这篇关于Java mapToInt()方法详解的文章就介绍到这了,更多相关Java mapToInt()内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
