博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Guava之FluentIterable使用示例
阅读量:4316 次
发布时间:2019-06-06

本文共 7253 字,大约阅读时间需要 24 分钟。

FluentIterable 是guava集合类中常用的一个类,主要用于过滤、转换集合中的数据;FluentIterable是一个抽象类,实现了Iterable接口,大多数方法都返回FluentIterable对象,这也是guava的思想之一。

transform:对于ListenableFuture的返回值进行转换。

allAsList:对多个ListenableFuture的合并,返回一个当所有Future成功时返回多个Future返回值组成的List对象。注:当其中一个Future失败或者取消的时候,将会进入失败或者取消。
successfulAsList:和allAsList相似,唯一差别是对于失败或取消的Future返回值用null代替。不会进入失败或者取消流程。
immediateFuture/immediateCancelledFuture: 立即返回一个待返回值的ListenableFuture。
makeChecked: 将ListenableFuture 转换成CheckedFuture。CheckedFuture 是一个ListenableFuture ,其中包含了多个版本的get 方法,方法声明抛出检查异常.这样使得创建一个在执行逻辑中可以抛出异常的Future更加容易
JdkFutureAdapters.listenInPoolThread(future): guava同时提供了将JDK Future转换为ListenableFuture的接口函数。
addCallBack为Future增加回调

首先构造集合中的元素类型

public class User {    private int age;    private String name;    public User() {    }    public User(int age, String name) {        this.age = age;        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    @Override    public String toString() {        final StringBuilder sb = new StringBuilder("User{");        sb.append("age=").append(age);        sb.append(", name='").append(name).append('\'');        sb.append('}');        return sb.toString();    }}

常用方法

1.过滤(filter)元素

filter方法要接收Predicate接口

/**  *    Returns the elements from this fluent iterable that satisfy a predicate.   * The resulting fluent iterable's iterator does not support remove(). */public final FluentIterable
filter(Predicate
predicate) { return from(Iterables.filter(getDelegate(), predicate));} /** * Returns the elements from this fluent iterable that are instances of class type. * */@GwtIncompatible // Class.isInstancepublic final
FluentIterable
filter(Class
type) { return from(Iterables.filter(getDelegate(), type));}

过滤出年龄是20岁的用户

public class Test {    public static void main(String[] args) {        List
userList = Lists.newArrayList(); userList.add(new User(18, "zhangsan")); userList.add(new User(20, "lisi")); userList.add(new User(22, "wangwu")); FluentIterable
filter = FluentIterable.from(userList).filter( new Predicate
() { @Override public boolean apply(User user) { return user.getAge() == 20; } }); for (User user : filter) { System.out.println(user); } }}

打印效果:

User{age=20, name='lisi'}

这里有一个潜在的坑,在高版本(21.0++)的guava中Predicate接口继承了java 8中的java.util.function.Predicate

@FunctionalInterface@GwtCompatiblepublic interface Predicate
extends java.util.function.Predicate

2.转换(transform)集合类型,transform接收Function接口,一般在方法中采用new接口实现回调方法apply的方式。

/** * Returns a fluent iterable that applies function to each element of this fluent * iterable. * * 

The returned fluent iterable's iterator supports remove() if this iterable's * iterator does. After a successful remove() call, this fluent iterable no longer * contains the corresponding element. */public final

FluentIterable
transform(Function
function) { return from(Iterables.transform(getDelegate(), function));}

public class Test {    public static void main(String[] args) {        List
userList = Lists.newArrayList(); userList.add(new User(18, "zhangsan")); userList.add(new User(20, "lisi")); userList.add(new User(22, "wangwu")); FluentIterable
transform = FluentIterable.from(userList).transform( new Function
() { @Override public String apply(User user) { return Joiner.on(",").join(user.getName(), user.getAge()); } }); for (String user : transform) { System.out.println(user); } }}

打印效果

zhangsan,18lisi,20wangwu,22

Function接口的定义

public interface Function

From-->To

拿到所有用户的年龄

public class Test {    public static void main(String[] args) {        List
userList = Lists.newArrayList(); userList.add(new User(18, "zhangsan")); userList.add(new User(20, "lisi")); userList.add(new User(22, "wangwu")); List
ages = FluentIterable.from(userList).transform( new Function
() { @Override public Integer apply(User input) { return input.getAge(); } }).toList(); System.out.println(ages); }}

打印结果

[18, 20, 22]
public final class Test {    public static 
void main(String[] args) { List
fromList = new ArrayList
(); List
result = FluentIterable.from(fromList).transform(new Function
() { @Override public T apply(F input) { // 可以根据需要写一个转换器 // 将类型F转换成T return XXConverter.convert(input); } }).toList(); }}class XXConverter
{ public static
T convert(F f) { return null; }}

 3.集合中的元素是否都满足某个条件

/** * Returns true if every element in this fluent iterable satisfies the predicate. If this * fluent iterable is empty, true is returned. */public final boolean allMatch(Predicate
predicate) { return Iterables.all(getDelegate(), predicate);}
public class Test {    public static void main(String[] args) {        List
userList = Lists.newArrayList(); userList.add(new User(18, "zhangsan")); userList.add(new User(20, "lisi")); userList.add(new User(22, "wangwu")); boolean allMatch = FluentIterable.from(userList).allMatch( new Predicate
() { @Override public boolean apply(User input) { return input.getAge() >= 18; } }); //true System.out.println(allMatch); }}

4.集合中的任何一个元素满足指定的条件即可

/** * Returns true if any element in this fluent iterable satisfies the predicate. */public final boolean anyMatch(Predicate
predicate) { return Iterables.any(getDelegate(), predicate);}
public class Test {    public static void main(String[] args) {        List
userList = Lists.newArrayList(); userList.add(new User(18, "zhangsan")); userList.add(new User(20, "lisi")); userList.add(new User(22, "wangwu")); boolean allMatch = FluentIterable.from(userList).anyMatch( new Predicate
() { @Override public boolean apply(User input) { return input.getAge() >= 22; } }); //true System.out.println(allMatch); }}

转载自:https://www.cnblogs.com/winner-0715/p/8412655.html

转载于:https://www.cnblogs.com/PengChengLi/p/11006000.html

你可能感兴趣的文章
数学基础 数论(二)
查看>>
走进模块
查看>>
什么是簇?
查看>>
[LeetCode] Construct Binary Tree from Inorder and Pretorder Traversal
查看>>
[转载]Android通过Socket上传文件
查看>>
golang 中的定时器(timer),更巧妙的处理timeout
查看>>
AT2134 Zigzag MST
查看>>
[NOI2019]回家路线
查看>>
何谓CRT,CRT的由来
查看>>
项目管理实践--VisualSVN Server
查看>>
2595 X之于Y 思维
查看>>
Selenium Webdriver模拟鼠标键盘操作
查看>>
vue链接规则_vue二级菜单添加链接+点击二级菜单渲染页面
查看>>
linux mysql 实例_linux下安装第二个mysql实例过程
查看>>
搜索mysql语句优化_Mysql查询语句优化
查看>>
mysql redhat rmp_MySQL在linux上的rpm包方式安装方法
查看>>
hibernate mysql demo_hibernate简单的demo
查看>>
python mysql 执行sql文件_mysql数据库怎么执行sql脚本
查看>>
mysql左右union_MYSQL:union, 左连接
查看>>
tkinter print 输出到文本框_tkinter 模块(一)
查看>>