关闭

Java函数式编程

102人阅读 评论(0) 收藏 举报

example1:定义了一系列价格,超过20则打九折

普通实现:

    final List<BigDecimal> prices = Arrays.asList(

        new BigDecimal("10"), new BigDecimal("30"), new BigDecimal("17"),

        new BigDecimal("20"), new BigDecimal("15"), new BigDecimal("18"),

        new BigDecimal("45"), new BigDecimal("12")

    );

          

    BigDecimal totalOfDiscountedPrices = BigDecimal.ZERO;

    for(BigDecimal price : prices) {

        if(price.compareTo(BigDecimal.valueOf(20)) > 0)

            totalOfDiscountedPrices =

                totalOfDiscountedPrices.add(price.multiply(BigDecimal.valueOf(0.9)));

    }

   

    System.out.println("Total of discounted prices: " + totalOfDiscountedPrices);

   

函数式实现:

final BigDecimal totalOfDiscountedPrices =

    prices.stream()

    .filter(price -> price.compareTo(BigDecimal.valueOf(20)) > 0)

    .map(price -> price.multiply(BigDecimal.valueOf(0.9)))

    .reduce(BigDecimal.ZERO, BigDecimal::add);

System.out.println("Total of discounted prices: " + totalOfDiscountedPrices);

   

   

   

example2:集合的使用

   

遍历列表

    final List<String> friends =

        Arrays.asList("Brian", "Nate", "Neal", "Raju", "Sara", "Scott");

          

    for(int i = 0; i < friends.size(); i++) {

        System.out.println(friends.get(i));

    }

          

    for(String name : friends) {

        System.out.println(name);

    }

          

    friends.forEach(new Consumer<String>() {

        public void accept(final String name) {

            System.out.println(name);

        }}

    );

          

    friends.forEach((final String name) -> System.out.println(name));

          

    friends.forEach((name) -> System.out.println(name));

          

    friends.forEach(name -> System.out.println(name));

          

   

    friends.forEach(System.out::println);

   

   

   

example3:列表的转化

普通实现:

final List<String> uppercaseNames = new ArrayList<String>();

     for(String name : friends) {

         uppercaseNames.add(name.toUpperCase());

     }

   

函数式实现:

    final List<String> uppercaseNames = new ArrayList<String>();

    friends.forEach(name -> uppercaseNames.add(name.toUpperCase()));

    System.out.println(uppercaseNames);

          

    friends.stream()

        .map(name -> name.toUpperCase())

        .forEach(name -> System.out.print(name + " "));

    System.out.println();

          

    friends.stream()

        .map(name -> name.length())

        .forEach(count -> System.out.print(count + " "));

          

    friends.stream()

        .map(String::toUpperCase)

   

    .forEach(name -> System.out.println(name));

   

   

   

example4:查找元素

普通实现:

final List<String> startsWithN = new ArrayList<String>();

for(String name : friends) {

    if(name.startsWith("N")) {

        startsWithN.add(name);

    }

}

   

函数式实现:

final List<String> startsWithN =

friends.stream()

    .filter(name -> name.startsWith("N"))

    .collect(Collectors.toList());

   

   

   

example5:消除代码冗余

冗余的实现:

final List<String> friends =

    Arrays.asList("Brian", "Nate", "Neal", "Raju", "Sara", "Scott");

final List<String> editors =

    Arrays.asList("Brian", "Jackie", "John", "Mike");

final List<String> comrades =

    Arrays.asList("Kate", "Ken", "Nick", "Paula", "Zach");

      

   

final long countFriendsStartN =

    friends.stream()

    .filter(name -> name.startsWith("N")).count();

final long countEditorsStartN =

    editors.stream()

    .filter(name -> name.startsWith("N")).count();

final long countComradesStartN =

    comrades.stream()

    .filter(name -> name.startsWith("N")).count();

   

消除冗余:

final Predicate<String> startsWithN = name -> name.startsWith("N");

final long countFriendsStartN =

    friends.stream()

    .filter(startsWithN)

    .count();

final long countEditorsStartN =

    editors.stream()

    .filter(startsWithN)

    .count();

final long countComradesStartN =

    comrades.stream()

    .filter(startsWithN)

    .count();

   

   

冗余的实现:

final Predicate<String> startsWithN = name -> name.startsWith("N");

final Predicate<String> startsWithB = name -> name.startsWith("B");

final long countFriendsStartN =

    friends.stream()

    .filter(startsWithN).count();

final long countFriendsStartB =

    friends.stream()

    .filter(startsWithB).count();

   

   

消除冗余:

public static Predicate<String> checkIfStartsWith(final String letter) {

    return name -> name.startsWith(letter);

}

      

final long countFriendsStartN =

    friends.stream()

    .filter(checkIfStartsWith("N"))

    .count();

final long countFriendsStartB =

    friends.stream()

    .filter(checkIfStartsWith("B"))

    .count();

   

重构,缩小作用域

版本1:

final Function<String, Predicate<String>> startsWithLetter = (String letter) -> {

    Predicate<String> checkStarts = (String name) -> name.startsWith(letter);

    return checkStarts;

};

   

版本2:

final Function<String, Predicate<String>> startsWithLetter = (String letter) -> (String name) ->

    name.startsWith(letter);

   

版本3:

final Function<String, Predicate<String>> startsWithLetter =

    letter -> name -> name.startsWith(letter);

   

final long countFriendsStartN =

    friends.stream()

    .filter(startsWithLetter.apply("N"))

    .count();

final long countFriendsStartB =

    friends.stream()

    .filter(startsWithLetter.apply("B"))

    .count();

   

   

example6:Optional

普通实现:

public static void pickName(final List<String> names, final String startingLetter) {

    String foundName = null;

    for(String name : names) {

        if(name.startsWith(startingLetter)) {

            foundName = name;

            break;

        }

    }

}

   

函数式实现:

public static void pickName(final List<String> names, final String startingLetter) {

    final 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")));

}

   

   

example7:MapReduce

finalOptional<String> aLongName =

    friends.stream()

    .reduce((name1, name2) -> name1.length() >= name2.length() ? name1 : name2);

aLongName.ifPresent(name -> System.out.println(String.format("A longest name: %s", name)));

      

final String steveOrLonger =

    friends.stream()

    .reduce("Steve", (name1, name2) -> name1.length() >= name2.length() ? name1 : name2);

   

   

example8:join

普通实现:

for(int i = 0; i < friends.size() - 1; i++) {

            System.out.print(friends.get(i) + ", ");

}

if(friends.size() > 0)

            System.out.println(friends.get(friends.size() - 1));

   

函数式实现:

System.out.println(String.join(", ", friends));

   

System.out.println(

    friends.stream()

        .map(String::toUpperCase)

        .collect(joining(", "))

);

   

example9:遍历字符串



final String str = "w00t";

str.chars().forEach(System.out::println);

   

example10:Comparator

public class Person {

    private final  String name;

    private final  int age;

      

    public Person(final String theName, final int theAge) {

        name =  theName;

        age =  theAge;

    }

      

    public String getName() { return name; }

      

    public int getAge() { return age; }

      

    public int ageDifference(final Person other) {

            return  age - other.age;

    }

      

    public  String toString() {

        return  String.format("%s - %d", name, age);

    }

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3902次
    • 积分:212
    • 等级:
    • 排名:千里之外
    • 原创:18篇
    • 转载:0篇
    • 译文:0篇
    • 评论:2条
    文章分类
    最新评论