`

Lambda Expressions - Collections

    博客分类:
  • FP
 
阅读更多

原创转载请注明出处:http://agilestyle.iteye.com/blog/2375466

 

IterationTest

package chapter2;

import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class IterationTest {
    private List<String> personList;

    @Before
    public void setUp() throws Exception {
        personList = Arrays.asList("Alex", "Darren", "Kevin", "Leon", "John", "Max");
    }

    @Test
    public void test1() {
        for (int i = 0; i < personList.size(); i++) {
            System.out.println(personList.get(i));
        }
    }

    @Test
    public void test2() {
        for (String person : personList) {
            System.out.println(person);
        }
    }

    @Test
    public void test3() {
        personList.forEach(new Consumer<String>() {
            @Override
            public void accept(final String person) {
                System.out.println(person);
            }
        });
    }

    @Test
    public void test4() {
        personList.forEach((final String name) -> System.out.println(name));
    }

    @Test
    public void test5() {
        personList.forEach((name) -> System.out.println(name));
    }

    @Test
    public void test6() {
        personList.forEach(name -> System.out.println(name));
    }

    @Test
    public void test7() {
        personList.forEach(System.out::println);
    }
}

Console Output


 

TransformTest

package chapter2;

import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TransformTest {
    private List<String> personList;

    @Before
    public void setUp() throws Exception {
        personList = Arrays.asList("Alex", "Darren", "Kevin", "Leon", "John", "Max");
    }

    @Test
    public void test1() {
        final List<String> upperNameList = new ArrayList<>();

        for (String person : personList) {
            upperNameList.add(person.toUpperCase());
        }

        System.out.println(upperNameList);
    }

    @Test
    public void test2() {
        personList.stream().map(person -> person.toUpperCase())
                .forEach(person -> System.out.print(person + " "));
    }

    @Test
    public void test3() {
        personList.stream().map(name -> name.length())
                .forEach(count -> System.out.print(count + " "));
    }

    @Test
    public void test4() {
        personList.stream().map(String::toUpperCase)
                .forEach(System.out::println);
    }
}

Console Output


 

FindTest

package chapter2;

import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class FindTest {
    private List<String> personList;
    private List<String> cityList;
    private List<String> roleList;

    @Before
    public void setUp() throws Exception {
        personList = Arrays.asList("Alex", "Darren", "Kevin", "Leon", "John", "Max");
        cityList = Arrays.asList("Beijing", "Shanghai", "Guangzhou", "Shenzhen", "Dalian");
        roleList = Arrays.asList("Engineer", "Manager", "Director", "President");
    }

    @Test
    public void test1() {
        List<String> startsWithJ = new ArrayList<>();

        for (String person : personList) {
            if (person.startsWith("J")) {
                startsWithJ.add(person);
            }
        }

        System.out.println(String.format("Found %d names", startsWithJ.size()));
    }

    @Test
    public void test2() {
        List<String> startsWithJ =
                personList.stream().filter(person -> person.startsWith("J")).collect(Collectors.toList());

        System.out.println(String.format("Found %d names", startsWithJ.size()));
    }

    @Test
    public void test3() {
        long count = personList.stream().filter(person -> person.startsWith("J")).count();

        System.out.println(count);
    }

    @Test
    public void test4() {
        long countPersonsStartD = personList.stream().filter(person -> person.startsWith("D")).count();
        long countCitiesStartD = cityList.stream().filter(city -> city.startsWith("D")).count();
        long countRolesStartD = roleList.stream().filter(role -> role.startsWith("D")).count();

        System.out.println(countPersonsStartD);
        System.out.println(countCitiesStartD);
        System.out.println(countRolesStartD);
    }

    @Test
    public void test5() {
        Predicate<String> startWithD = name -> name.startsWith("D");

        long countPersonsStartD = personList.stream().filter(startWithD).count();
        long countCitiesStartD = cityList.stream().filter(startWithD).count();
        long countRolesStartD = roleList.stream().filter(startWithD).count();

        System.out.println(countPersonsStartD);
        System.out.println(countCitiesStartD);
        System.out.println(countRolesStartD);
    }

    @Test
    public void test6() {
        Predicate<String> startWithD = name -> name.startsWith("D");
        Predicate<String> startWithM = name -> name.startsWith("M");

        long countPersonsStartD = personList.stream().filter(startWithD).count();
        long countPersonsStartM = personList.stream().filter(startWithM).count();

        System.out.println(countPersonsStartD);
        System.out.println(countPersonsStartM);
    }

    public static Predicate<String> checkIfStartsWith(final String letter) {
        return name -> name.startsWith(letter);
    }

    @Test
    public void test7() {
        long countPersonsStartD = personList.stream().filter(checkIfStartsWith("D")).count();
        long countPersonsStartM = personList.stream().filter(checkIfStartsWith("M")).count();

        System.out.println(countPersonsStartD);
        System.out.println(countPersonsStartM);
    }

    @Test
    public void test8() {
//        Function<String, Predicate<String>> startsWithLetter =
//                (String letter) -> {
//                    Predicate<String> checkStarts = (String name) -> name.startsWith(letter);
//                    return checkStarts;
//                };

//        Function<String, Predicate<String>> startsWithLetter =
//                (String letter) -> (String name) -> name.startsWith(letter);

        Function<String, Predicate<String>> startsWithLetter =
                letter -> name -> name.startsWith(letter);

        long countPersonsStartD = personList.stream().filter(startsWithLetter.apply("D")).count();
        long countPersonsStartM = personList.stream().filter(startsWithLetter.apply("M")).count();

        System.out.println(countPersonsStartD);
        System.out.println(countPersonsStartM);
    }
}

Console Output

 

OptionalTest

package chapter2;

import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class OptionalTest {
    private List<String> personList;

    @Before
    public void setUp() throws Exception {
        personList = Arrays.asList("Alex", "Darren", "Kevin", "Leon", "John", "Max");
    }

    public static void pickNameImperative(final List<String> names, final String startingLetter) {
        String foundName = null;

        for (String name : names) {
            if (name.startsWith(startingLetter)) {
                foundName = name;
                break;
            }
        }

        System.out.print(String.format("A name starting with %s: ", startingLetter));

        if (foundName != null) {
            System.out.println(foundName);
        } else {
            System.out.println("No name found");
        }
    }

    @Test
    public void test1() {
        pickNameImperative(personList, "D");
        pickNameImperative(personList, "B");
    }

    public static void pickNameDeclarative(final List<String> names, final String startingLetter) {
        Optional<String> foundName =
                names.stream().filter(name -> name.startsWith(startingLetter)).findFirst();

        System.out.println(String.format("A name starting with %s: %s", startingLetter, foundName.orElse("No name found")));
    }

    @Test
    public void test2() {
        pickNameDeclarative(personList, "D");
        pickNameDeclarative(personList, "B");
    }

    @Test
    public void test3() {
        Optional<String> foundName = personList.stream().filter(name -> name.startsWith("D")).findFirst();

        foundName.ifPresent(name -> System.out.println("Hello " + name));
    }

}

Console Output


 

ReduceTest

package chapter2;

import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class ReduceTest {

    private List<String> personList;

    @Before
    public void setUp() throws Exception {
        personList = Arrays.asList("Alex", "Darren", "Kevin", "Leon", "John", "Max");
    }

    @Test
    public void test1() {
        System.out.println("Total numbers of characters in all times: " + personList.stream().mapToInt(name -> name.length()).sum());
    }

    @Test
    public void test2() {
        Optional<String> longestName = personList.stream().reduce((name1, name2) -> name1.length() >= name2.length() ? name1 : name2);

        longestName.ifPresent(name -> System.out.println(String.format("The longest person name: %s", name)));
    }

    @Test
    public void test3() {
        String elegantOrLonger = personList.stream().reduce("Elegant", (name1, name2) -> name1.length() >= name2.length() ? name1 : name2);

        System.out.println(elegantOrLonger);
    }
}

Console Output


 

PrintTest

package chapter2;

import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class PrintTest {
    private List<String> personList;

    @Before
    public void setUp() throws Exception {
        personList = Arrays.asList("Alex", "Darren", "Kevin", "Leon", "John", "Max");
    }

    @Test
    public void test1() {
        for (String person : personList) {
            System.out.print(person + ", ");
        }

        System.out.println();
    }

    @Test
    public void test2() {
        for (int i = 0; i < personList.size() - 1; i++) {
            System.out.print(personList.get(i) + ", ");
        }

        if (personList.size() > 0) {
            System.out.println(personList.get(personList.size() - 1));
        }
    }

    @Test
    public void test3() {
        System.out.println(String.join(", ", personList));
    }

    @Test
    public void test4() {
        System.out.println(personList.stream().map(String::toUpperCase).collect(Collectors.joining(", ")));
    }
}

Console Output


 

Reference

Pragmatic.Functional.Programming.in.Java.Mar.2014 

 

  • 大小: 28.9 KB
  • 大小: 31 KB
  • 大小: 29 KB
  • 大小: 28.4 KB
  • 大小: 24.2 KB
  • 大小: 28.1 KB
分享到:
评论

相关推荐

    Mastering Lambdas- Java Programming in a Multicore World

    - **Stream API Utilization**: With lambda expressions, it's easier to work with the Stream API, which provides a high-level abstraction for processing collections. Streams allow developers to perform ...

    Java SE 8 for the Really Impatient

    The addition of lambda expressions (closures) and streams represents the biggest change to Java programming since the introduction of generics and annotations. Now, with Java SE 8 for the Really ...

    Java Language Features 2nd Edition

    Work with essential and advanced features of the Java programming language such as Java modules development, lambda expressions (closures), inner classes, threads, I/O, Collections, garbage collection...

    jdk1.8.docx

    1. **Lambda Expressions**: One of the most notable additions in Java 8 is the introduction of lambda expressions, which enable functional programming concepts in Java. Lambda expressions allow you to ...

    Pro.Java.8.Programming.3rd.Edition.1484206428

    You will also delve into more advanced topics like lambda expressions, closures, new i/o (NIO.2), enums, generics, XML, metadata and the Swing APIs for GUI design and development. By the end of the ...

    Pro.Java.8.Programming.3rd.Edition.1484206428.epub

    You will also delve into more advanced topics like lambda expressions, closures, new i/o (NIO.2), enums, generics, XML, metadata and the Swing APIs for GUI design and development. By the end of the ...

    AW - Essential C# 4.0, 3rd Edition Mar 2010+完美版

    Delegates, events, and lambda expressions Collection interfaces and standard query operators Query expressions and the tree expressions on which LINQ providers are based Reflection, attributes, and...

    jdk1.8_win32.rar

    - **Lambda Expressions**: JDK 1.8 introduced lambda expressions, which allow for concise and functional-style coding. These expressions are used to represent anonymous functions, making it easier to ...

    jdk1.8_win64.rar

    1. **Lambda Expressions**: One of the most prominent features introduced in Java 8 is lambda expressions, which enable more concise and functional programming styles. They allow you to represent ...

    Core Java Volume I Fundamentals, 11th Edition

    In this first of two volumes, Horstmann offers in-depth coverage of fundamental Java and UI programming, including objects, generics, collections, lambda expressions, Swing design, concurrency, and ...

    Java in Two Semesters Featuring JavaFX, 4th Edition

    This fully updated and greatly enhanced fourth edition covers the key developments introduced in Java 8, including material on JavaFX, lambda expressions and the Stream API. Topics and features: ...

    OReilly Java Cookbook 3rd Edition

    From lambda expressions and JavaFX 8 to new support for network programming and mobile development, Java 8 brings a wealth of changes. This cookbook helps you get up to speed right away with hundreds ...

    jdk1.8-windows版64位

    2. **Method References:** In addition to lambda expressions, JDK 1.8 introduces method references, which enable you to directly refer to a method as an argument to a functional interface. This feature...

Global site tag (gtag.js) - Google Analytics