Lambda Expressions - Strings, Comparators, Filters

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

 

IterationStringTest

package chapter3;

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

public class IterationStringTest {

    private String str;

    @Before
    public void setUp() throws Exception {
        str = "Hello, 123, world";
    }

    @Test
    public void test1() {
        str.chars().forEach(ch -> System.out.println(ch));
    }

    @Test
    public void test2() {
        str.chars().forEach(System.out::println);
    }

    private static void printChar(int input) {
        System.out.println((char) input);
    }

    @Test
    public void test3() {
        str.chars().forEach(IterationStringTest::printChar);
    }

    @Test
    public void test4() {
        str.chars().mapToObj(ch -> Character.valueOf((char) ch)).forEach(System.out::println);
    }

    @Test
    public void test5() {
        str.chars().filter(ch -> Character.isDigit(ch)).forEach(ch -> printChar(ch));
    }

    @Test
    public void test6() {
        str.chars().filter(Character::isDigit).forEach(IterationStringTest::printChar);
    }
} 

Console Output


 

CompareTest

package chapter3;

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

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CompareTest {

    private List<Person> personList;

    @Before
    public void setUp() throws Exception {
        personList = Arrays.asList(
                new Person("Alex", 20),
                new Person("Kevin", 27),
                new Person("Darren", 27),
                new Person("Max", 35));
    }

    @Test
    public void test1() {
        System.out.println("sorted in asc");
        personList.stream()
                .sorted((person1, person2) -> person1.ageDifference(person2))
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    @Test
    public void test2() {
        System.out.println("sorted in asc");
        personList.stream()
                .sorted(Person::ageDifference)
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    @Test
    public void test3() {
        System.out.println("sorted in desc");
        personList.stream()
                .sorted((person1, person2) -> person2.ageDifference(person1))
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    @Test
    public void test4() {
        Comparator<Person> compareAsc = (person1, person2) -> person1.ageDifference(person2);
        Comparator<Person> compareDesc = compareAsc.reversed();

        System.out.println("sorted in asc");
        personList.stream()
                .sorted(compareAsc)
                .collect(Collectors.toList())
                .forEach(System.out::println);

        System.out.println("sorted in desc");
        personList.stream()
                .sorted(compareDesc)
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    @Test
    public void test5() {
        System.out.println("sorted in asc order by name");
        personList.stream()
                .sorted((person1, person2) -> person1.getName().compareTo(person2.getName()))
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    @Test
    public void test6() {
        System.out.println("sorted in desc order by name");
        personList.stream()
                .sorted((person1, person2) -> person2.getName().compareTo(person1.getName()))
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    @Test
    public void test7() {
        personList.stream()
                .min(Person::ageDifference)
                .ifPresent(youngest -> System.out.println("Youngest: " + youngest));
    }

    @Test
    public void test8() {
        personList.stream()
                .max(Person::ageDifference)
                .ifPresent(oldest -> System.out.println("Oldest: " + oldest));
    }

    @Test
    public void test9() {
        personList.stream()
                .sorted(Comparator.comparing((Person person) -> person.getName()))
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    @Test
    public void test10() {
        Function<Person, String> byName = person -> person.getName();
        personList.stream()
                .sorted(Comparator.comparing(byName))
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    @Test
    public void test11() {
        Function<Person, Integer> byAge = person -> person.getAge();
        Function<Person, String> byName = person -> person.getName();

        System.out.println("sorted in asc order by age and name");
        personList.stream()
                .sorted(Comparator.comparing(byAge).thenComparing(byName))
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    private static class Person {
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }

        public int ageDifference(Person other) {
            return age - other.age;
        }

        @Override
        public String toString() {
            return String.format("%s - %d", name, age);
        }
    }
}

Console Output


 

CollectorsTest

package chapter3;

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

public class CollectorsTest {

    private List<Person> personList;

    @Before
    public void setUp() throws Exception {
        personList = Arrays.asList(
                new Person("Alex", 20),
                new Person("Kevin", 27),
                new Person("Darren", 27),
                new Person("Max", 35));
    }

    @Test
    public void test1() {
        List<Person> resultList = new ArrayList<>();
        personList.stream()
                .filter(person -> person.getAge() > 20)
                .forEach(person -> resultList.add(person));

        // older than 20: [Kevin - 27, Darren - 27, Max - 35]
        System.out.println("older than 20: " + resultList);
    }

    @Test
    public void test2() {
        List<Person> resultList =
                personList.stream()
                        .filter(person -> person.getAge() > 20)
                        .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

        // [Kevin - 27, Darren - 27, Max - 35]
        System.out.println(resultList);
    }

    @Test
    public void test3() {
        List<Person> resultList =
                personList.stream()
                        .filter(person -> person.getAge() > 20)
                        .collect(Collectors.toList());

        // [Kevin - 27, Darren - 27, Max - 35]
        System.out.println(resultList);
    }

    @Test
    public void test4() {
        Map<Integer, List<Person>> resultMap =
                personList.stream()
                        .collect(Collectors.groupingBy(Person::getAge));

        // group by age: {35=[Max - 35], 20=[Alex - 20], 27=[Kevin - 27, Darren - 27]}
        System.out.println("group by age: " + resultMap);
    }

    @Test
    public void test5() {
        Map<Integer, List<String>> resultMap =
                personList.stream()
                        .collect(Collectors.groupingBy(Person::getAge, Collectors.mapping(Person::getName, Collectors.toList())));

        // {35=[Max], 20=[Alex], 27=[Kevin, Darren]}
        System.out.println(resultMap);
    }

    @Test
    public void test6() {
        Comparator<Person> byAge = Comparator.comparing(Person::getAge);

        Map<Character, Optional<Person>> resultMap = personList.stream().
                collect(Collectors.groupingBy(person -> person.getName().charAt(0),
                        Collectors.reducing(BinaryOperator.maxBy(byAge))));

        System.out.println("Oldest person of each letter: " + resultMap);
    }

    private static class Person {
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }

        public int ageDifference(Person other) {
            return age - other.age;
        }

        @Override
        public String toString() {
            return String.format("%s - %d", name, age);
        }
    }
}

Console Output


 
FileDirTest

package chapter3;

import org.junit.Test;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FileDirTest {

    @Test
    public void test1() throws IOException {
        Files.list(Paths.get(".")).forEach(System.out::println);
    }

    @Test
    public void test2() throws IOException {
        Files.list(Paths.get(".")).filter(Files::isDirectory).forEach(System.out::println);
    }

    @Test
    public void test3() throws IOException {
        String[] files = new File(".").list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".java");
            }
        });

        System.out.println(files);
    }

    @Test
    public void test4() throws IOException {
        Files.newDirectoryStream(
                Paths.get("."), path -> path.toString().endsWith(".java"))
                .forEach(System.out::println);
    }

    @Test
    public void test5() throws IOException {
        File[] files = new File(".").listFiles(file -> file.isHidden());
        new File(".").listFiles(File::isHidden);
        Arrays.stream(files).forEach(System.out::println);
    }

    @Test
    public void test6() throws IOException {
        List<File> files = new ArrayList<>();
        File[] filesInCurrentDir = new File(".").listFiles();

        for (File file : filesInCurrentDir) {
            File[] filesInSubDir = file.listFiles();

            if (filesInSubDir != null) {
                files.addAll(Arrays.asList(filesInSubDir));
            } else {
                files.add(file);
            }
        }

        System.out.println("Count: " + files.size());
    }

    @Test
    public void test7() throws IOException {
        List<File> files =
                Stream.of(new File(".").listFiles())
                        .flatMap(file -> file.listFiles() == null ? Stream.of(file) : Stream.of(file.listFiles()))
                        .collect(Collectors.toList());

        System.out.println("Count: " + files.size());
    }
}

Console Output


 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值