guava (四)--集合中的FluentIterable类
来源:互联网 发布:如何进入服务器数据库 编辑:程序博客网 时间:2024/05/14 14:45
FluentIterable 是guava集合类中常用的一个类,主要用于过滤、转换集合中的数据;FluentIterable 是一个抽象类,实现了Iterable接口,大多数方法都返回FluentIterable对象,这也是guava的思想之一。
下面主要针对filter 和transform方法进行演示。
filter方法要接收Predicate接口,transform接收Function接口,一般在方法中采用new接口实现回调方法apply的方式。
import com.google.common.base.Function;import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
public class FluentTest {
private List<User> userList;
@Before
public void setUser() {
User u1 = new User(20, "lili");
User u2 = new User(19, "haha");
User u3 = new User(20, "niu");
User u4 = new User(23, "keke");
userList = Lists.newArrayList(u1, u2, u3, u4);
}
@Test
public void fluentFliter() {
/**
* 获取 年龄==20的用户;返回为Iterable接口
*/
FluentIterable<User> filter = FluentIterable.from(userList).filter(new Predicate<User>() {
@Override
public boolean apply(User user) {
return user.getAge() == 20;
}
});
//打印结果
for (User user : filter) {
System.out.println(user.getAge());
}
/**
* 输出
* 20
20
*/
}
@Test
public void fluentTransform() {
/**
* 转换集合类型 ,把list中的user对象转换为String
*/
FluentIterable<String> transform = FluentIterable.from(userList).transform(new Function<User, String>() {
@Override
public String apply(User input) {
return Joiner.on("==").join(input.getAge(), input.getName());
}
});
//打印结果
for (String s : transform) {
System.out.println(s);
}
/**
* 输出
20==lili
19==haha
20==niu
23==keke
*/
}
static class User {
int age;
String name;
User(int age, String name) {
this.age = age;
this.name = name;
}
int getAge() {
return age;
}
void setAge(int age) {
this.age = age;
}
String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
}
}
0 0
- guava (四)--集合中的FluentIterable类
- Guava ---- FluentIterable迭代器
- Guava collections -- FluentIterable
- Guava(四):集合基础总结之List
- Guava(四):集合基础总结之Map
- guava (三) 集合工具类
- Google Guava集合在实体类中的应用示例
- guava集合
- Guava集合
- guava 集合
- Google Guava学习(6)-Guava集合工具 Multiset
- Google Guava学习(7)-Guava集合工具 Bimap接口
- Google Guava学习(8)-Guava集合工具 Table接口
- 集合类(四)
- Java集合类汇总记录--guava篇
- [Google Guava] 2.4-集合扩展工具类
- Guava学习——集合类BiMap
- Google Guava有用的几个集合类
- Megacli中建立虚拟盘参数的含义
- 【Ajax技术】准备AJAX服务器端和客户端环境
- web第三方登录接入
- 算法训练 最短路 (spfa算法)
- [NSNotificationCenter defaultCenter] 通知接收不全面原因
- guava (四)--集合中的FluentIterable类
- PHP转换成JSON数组,及PHP解析JSON数组。
- Win10体验之联想
- oracle insert into select模板
- 关于web应用上下文Context
- 使用Python创建简单的HTTP和FTP服务
- 指针的几个重要概念
- 喷水装置(一)
- C/C++内存泄漏及检测