java guava 函数式编程

Guava:google的工程师利用传说中的“20%时间”开发的集合库,它是对jdk提供的扩展,提供了很多实用的类来简化代码。

开源地址:https://github.com/google/guava

jar包下载:http://maven.outofmemory.cn/com.google.guava/guava/


package com.uwo9.test08;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * 函数式编程 :解耦 
 * 1.Predicate 
 * 2.Function 
 * 工具:
 * Collections2.filter()过滤器
 * Collections2.transform()转换
 * Functions.compose()组合式函数编程
 */
public class Test02 {

	public static void main(String[] args) {
		//test1();
		//test2();
		test3();
	}

	/**
	 * 组合式函数编程
	 */
	public static void test3() {
		// 组合式函数编程
		// 确保容器中的字符串长度不超过5,超过进行截取,后全部大写
		List<String> list = Lists.newArrayList("uwo9", "goods", "happiness");
		// 确保容器中的字符串长度不超过5,超过进行截取
		Function<String, String> f1 = new Function<String, String>() {

			@Override
			public String apply(String input) {
				return input.length() > 5 ? input.substring(0, 5) : input;
			}
		};
		//转成大写
		Function<String, String> f2 = new Function<String, String>() {

			@Override
			public String apply(String input) {
				return input.toUpperCase();
			}
		};
		
		Function<String, String> f=Functions.compose(f1, f2);
		Collection<String>resultCol=Collections2.transform(list, f);
		for (String temp : resultCol) {
			System.out.println(temp);
		}
	}

	/**
	 * 转换
	 */
	public static void test2() {
		// 类型转换
		Set<Long> timeSet = Sets.newHashSet();
		timeSet.add(1000000000L);
		timeSet.add(9999999999999L);
		timeSet.add(200000000000L);

		Collection<String> timeStrCol = Collections2.transform(timeSet, new Function<Long, String>() {

			@Override
			public String apply(Long input) {
				// TODO Auto-generated method stub
				return new SimpleDateFormat("yyyy-MM-dd").format(input);
			}
		});

		for (String temp : timeStrCol) {
			System.out.println(temp);
		}
	}

	/**
	 * 过滤器
	 */
	public static void test1() {
		// 创建List静态初始化
		List<String> list = Lists.newArrayList("moom", "son", "uwo9", "dad", "refer");
		// 找出回文 palindrome backwords mirror words
		// 匿名内部类对象:匿名内部类,同时创建对象
		Collection<String> palindromeList = Collections2.filter(list, new Predicate<String>() {

			@Override
			public boolean apply(String input) {
				// 业务逻辑
				return new StringBuilder(input).reverse().toString().equals(input);
			}
		});

		for (String temp : palindromeList) {
			System.out.println(temp);
		}
	}

}






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值