search
HomeJavajavaTutorialItem Give preference to functions without side effects in streams

Item  Dê preferência às funções sem efeitos colaterais nas streams

Introduction to using streams:

  • New users may find it difficult to express calculations in stream pipelines.
  • Streams are based on functional programming, offering expressiveness, speed and parallelization.

Structuring of the calculation:

  • Structure calculations as sequences of transformations using pure functions.
  • Pure functions depend only on their inputs and do not change state.

Side effects:

  • Avoid side effects in functions passed to stream operations.
  • Improper use of forEach that changes external state is a "bad smell".

Example 1: Code with side effects

Map<string long> freq = new HashMap();
try (Stream<string> words = new Scanner(file).tokens()) {
    words.forEach(word -> {
        freq.merge(word.toLowerCase(), 1L, Long::sum);
    });
}

</string></string>

Problem: This code uses forEach to modify the external state (freq). It is iterative and does not take advantage of streams.

Example 2: Code without side effects

Map<string long> freq;
try (Stream<string> words = new Scanner(file).tokens()) {
    freq = words.collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting()));
}

</string></string>

Solution: Uses the Collectors.groupingBy collector to create the frequency table without changing the external state. Shorter, clearer and more efficient.

Appropriation of the streams API:

  • Code that imitates iterative loops does not take advantage of streams.
  • Use collectors for more efficient and readable operations.

Collectors:

  • Simplify collecting results into collections such as lists and sets.
  • Collectors.toList(), Collectors.toSet(), Collectors.toCollection(collectionFactory).

Example 3: Extracting a list of the ten most frequent words

List<string> topTen = freq.entrySet().stream()
    .sorted(Map.Entry.<string long>comparingByValue().reversed())
    .limit(10)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

</string></string>

Explanation:

  • Orders the frequency map entries in descending order of value.
  • Limits the stream to 10 words.
  • Collects the most frequent words in a list.

Complexity of the Collectors API:

  • API has 39 methods, but many are for advanced use.
  • Collectors can be used to create maps (toMap, groupingBy).

Maps and collection strategies:

  • toMap(keyMapper, valueMapper) for unique key-values.
  • Strategies for dealing with key conflicts using the merge function.
  • groupingBy to group elements into categories based on classifier functions.

Example 4: Using toMap with merge function

Map<string long> freq;
try (Stream<string> words = new Scanner(file).tokens()) {
    freq = words.collect(Collectors.toMap(
        String::toLowerCase, 
        word -> 1L, 
        Long::sum
    ));
}

</string></string>

Explanation:

  • toMap maps words to their frequencies.
  • Merge function (Long::sum) deals with key conflicts by summing the frequencies.

Example 5: Grouping albums by artist and finding the best-selling album

Map<artist album> topAlbums = albums.stream()
    .collect(Collectors.toMap(
        Album::getArtist,
        Function.identity(),
        BinaryOperator.maxBy(Comparator.comparing(Album::sales))
    ));

</artist>

Explanation:

  • toMap maps artists to their best-selling albums.
  • BinaryOperator.maxBy determines the best-selling album for each artist.

String Collection:
Collectors.joining to concatenate strings with optional delimiters.

Example 6: Concatenating strings with delimiter

String result = Stream.of("came", "saw", "conquered")
    .collect(Collectors.joining(", ", "[", "]"));

Explanation:

  • Collectors.joining concatenates strings with a comma as delimiter, prefix and suffix.
  • Result: [came, saw, conquered].

Conclusion:

  • Essence of streams is in functions without side effects.
  • forEach should only be used to report results.
  • Knowledge about collectors is essential for effective use of streams.

The above is the detailed content of Item Give preference to functions without side effects in streams. 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
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

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 Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software