search
HomeJavajavaTutorialStream API in Java 8: How to map collection to int type using mapToInt() method

Stream API in Java 8: How to use mapToInt() method to map a collection to int type

Introduction:
Java 8 introduced the Stream API to provide developers with a more concise and efficient Collection operation mode. One of the commonly used methods is mapToInt(), which maps the elements in the collection to type int and returns an IntStream. This article will introduce how to use the mapToInt() method and provide some usage examples.

1. Introduction to mapToInt() method

mapToInt() is a method provided in the Stream API, which can be used to map elements in a collection to int type. The declaration of this method is as follows:

IntStream mapToInt(ToIntFunction super T> mapper)

Among them, ToIntFunction is a function interface, representing a function with input type T and output type int. . When using the mapToInt() method, we need to pass in a ToIntFunction implementation to convert the elements in the collection to int.

2. Usage Examples

The following are some examples of using the mapToInt() method:

Example 1: Map the length of elements in a string collection to the int type

List<String> list = Arrays.asList("Apple", "Banana", "Orange", "Grapes");
IntStream intStream = list.stream().mapToInt(String::length);
intStream.forEach(System.out::println);

In this example, we first create a string collection list and convert it to a Stream using the stream() method. Then, use the mapToInt() method to map the length of each element in the collection to type int and return an IntStream. Finally, we output each mapped int value through the forEach method.

Example 2: Mapping an attribute in the object collection to int type

Suppose we have a Person class, which has an age attribute. We can map the age attribute of each person in the Person object collection to the int type through the mapToInt() method.

class Person {
    private int age;
    
    public Person(int age) {
        this.age = age;
    }
    
    public int getAge() {
        return age;
    }
}

List<Person> list = Arrays.asList(
        new Person(20),
        new Person(30),
        new Person(40)
);

IntStream intStream = list.stream().mapToInt(Person::getAge);
intStream.forEach(System.out::println);

In this example, we first create a Person class and define an age attribute and a getAge() method in the class. Then, a collection list of Person objects is created and converted into a Stream through the stream() method. Next, use the mapToInt() method to map the age attribute of each Person object in the collection to the int type and return an IntStream. Finally, we output each mapped int value through the forEach method.

3. Summary

This article introduces the mapToInt() method of the Stream API in Java 8. This method can map the elements in the collection to the int type and return an IntStream. We demonstrated how to use the mapToInt() method through examples, including mapping the length of elements in the string collection to the int type and mapping a property in the object collection to the int type.

Using the Stream API and mapToInt() method, we can perform collection operations more concisely and efficiently in code. I hope this article is helpful for you to understand and use the Stream API in Java 8.

Reference materials:

  • Official documentation of Stream API in Java 8: https://docs.oracle.com/javase/8/docs/api/java/util/stream /package-summary.html

The above is the detailed content of Stream API in Java 8: How to map collection to int type using mapToInt() method. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools