Guava之FluentIterable使用示例
FluentIterable 是guava集合类中常用的一个类,主要用于过滤、转换集合中的数据;FluentIterable是一个抽象类,实现了Iterable接口,大多数方法都返回FluentIterable对象,这也是guava的思想之一。
首先构造集合中的元素类型
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<E> filter(Predicate<? super E> predicate) {
return from(Iterables.filter(getDelegate(), predicate));
}
/**
* Returns the elements from this fluent iterable that are instances of class type.
*
*/
@GwtIncompatible // Class.isInstance
public final <T> FluentIterable<T> filter(Class<T> type) {
return from(Iterables.filter(getDelegate(), type));
}
过滤出年龄是20岁的用户
public class Test {
public static void main(String[] args) {
List<User> userList = Lists.newArrayList();
userList.add(new User(18, "zhangsan"));
userList.add(new User(20, "lisi"));
userList.add(new User(22, "wangwu"));
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);
}
}
}
打印效果:
User{age=20, name='lisi'}
这里有一个潜在的坑,在高版本(21.0++)的guava中Predicate接口继承了java 8中的java.util.function.Predicate
@FunctionalInterface
@GwtCompatible
public interface Predicate<T> extends java.util.function.Predicate<T>
2.转换(transform)集合类型,transform接收Function接口,一般在方法中采用new接口实现回调方法apply的方式。
/**
* Returns a fluent iterable that applies function to each element of this fluent
* iterable.
*
* <p>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 <T> FluentIterable<T> transform(Function<? super E, T> function) {
return from(Iterables.transform(getDelegate(), function));
}
public class Test {
public static void main(String[] args) {
List<User> userList = Lists.newArrayList();
userList.add(new User(18, "zhangsan"));
userList.add(new User(20, "lisi"));
userList.add(new User(22, "wangwu"));
FluentIterable<String> transform = FluentIterable.from(userList).transform(
new Function<User, String>() {
@Override
public String apply(User user) {
return Joiner.on(",").join(user.getName(), user.getAge());
}
});
for (String user : transform) {
System.out.println(user);
}
}
}
打印效果
zhangsan,18
lisi,20
wangwu,22
Function接口的定义
public interface Function<F, T>
From-->To
拿到所有用户的年龄
public class Test {
public static void main(String[] args) {
List<User> userList = Lists.newArrayList();
userList.add(new User(18, "zhangsan"));
userList.add(new User(20, "lisi"));
userList.add(new User(22, "wangwu"));
List<Integer> ages = FluentIterable.from(userList).transform(
new Function<User, Integer>() {
@Override
public Integer apply(User input) {
return input.getAge();
}
}).toList();
System.out.println(ages);
}
}
打印结果
[18, 20, 22]
public final class Test {
public static <F, T> void main(String[] args) {
List<F> fromList = new ArrayList<F>();
List<T> result = FluentIterable.from(fromList).transform(new Function<F, T>() {
@Override
public T apply(F input) {
// 可以根据需要写一个转换器
// 将类型F转换成T
return XXConverter.convert(input);
}
}).toList();
}
}
class XXConverter<F, T> {
public static <F, T> 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<? super E> predicate) {
return Iterables.all(getDelegate(), predicate);
}
public class Test {
public static void main(String[] args) {
List<User> 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<User>() {
@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<? super E> predicate) {
return Iterables.any(getDelegate(), predicate);
}
public class Test {
public static void main(String[] args) {
List<User> 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<User>() {
@Override
public boolean apply(User input) {
return input.getAge() >= 22;
}
});
//true
System.out.println(allMatch);
}
}
参考:
Guava之FluentIterable使用示例的更多相关文章
- guava学习--FluentIterable
public class FluentIterableTest { public static void main(String[] args) { Man man1 = new Man(" ...
- Guava之ImmutableMap使用示例
ImmutableMap 的作用就是:可以让java代码也能够创建一个对象常量映射,来保存一些常量映射的键值对. 分析以下情景,来具体讨论这个的好处. 假设现在有需求如下:根据数据库存的某个key字段 ...
- Guava API - FluentIterable Predicate Function Odering Range Splitter
这写API可解决的问题 1. 集合元素的过滤 - FluentIterable Predicate Range Function 1) 先说Predicate<T>,这个相当与一个过滤原则 ...
- Guava RateLimiter限流器使用示例
Guava中的RateLimiter可以限制单进程中某个方法的速率,本文主要介绍如何使用,实现原理请参考文档:推荐:超详细的Guava RateLimiter限流原理解析和推荐:RateLimiter ...
- Guava之Iterables使用示例
这是一个常量工具类.Iterables类包含了一系列的静态方法,来操作或返回Iterable对象. public final class Iterables { private Iterables() ...
- Guava Cache 使用笔记
https://www.cnblogs.com/parryyang/p/5777019.html https://www.cnblogs.com/shoren/p/guava_cache.html J ...
- Atitit s2018 s4 doc list dvchomepc dvccompc.docx .docx \s2018 s4 doc compc dtS44 \s2018 s4 doc dvcCompc dtS420 \s2018 s4f doc homepc \s2018 s4 doc compc dtS44\(5 封私信 _ 44 条消息)WebSocket 有没有可能取代 AJAX
Atitit s2018 s4 doc list dvchomepc dvccompc.docx .docx \s2018 s4 doc compc dtS44 \s2018 s4 doc dvcCo ...
- Spring cloud微服务安全实战-3-3 API安全机制之流控
首先要保证你的服务是可用的,其中一个重要的手段就是流控.就是流量控制.比如我的系统每秒只能处理500个请求,那么多余的请求就拒绝掉.这样我的系统不会被压死 实际的开发中,所要面对的流控场景实际是非常复 ...
- Guava并发:ListenableFuture与RateLimiter示例
ListenableFuture顾名思义就是可以监听的Future,它是对java原生Future的扩展增强 RateLimiter类似于JDK的信号量Semphore,他用来限制对资源并发访问的线程 ...
随机推荐
- C++ map.insert: pair和make_pair区别
C++ map.insert: pair和make_pair区别 \*********************************\ map<uint32_t, string> tem ...
- 【LeetCode刷题】SQL-Second Highest Salary 及扩展以及Oracle中的用法
转载于:https://www.cnblogs.com/contixue/p/7057025.html Write a SQL query to get the second highest sala ...
- linux入门系列
Linux基础入门 常用Linux命令 linux学习笔记-1.man_page linux学习笔记-2.常用命令 linux学习笔记-3.文件相关命令 linux学习笔记-4.系统命令 linux学 ...
- CentOS 7下KVM支持虚拟化/嵌套虚拟化配置
开启虚拟化: cat << EOF > /etc/modprobe.d/kvm-nested.conf options kvm-intel nested=1 options kvm- ...
- STM32 F4 GPIO Modes
STM32 F4 GPIO Modes Goal: creating a visual summary of GPIO configuration modes. The summary at the ...
- Golang 特性简介
by sheepbao 主要大概介绍go语言的历史和特性,简单的入门. 来历 很久以前,有一个IT公司,这公司有个传统,允许员工拥有20%自由时间来开发实验性项目.在2007的某一天,公司的几个大牛, ...
- [置顶] Android系统移植与调试之------->build.prop文件详细赏析
小知识:什么是build.prop? /system/build.prop 是一个属性文件,在Android系统中.prop文件很重要,记录了系统的设置和改变,类似於/etc中的文件.这个文件是如 ...
- Revit API根据参数类型取得参数的值
参数的类型string与int取得的方法有所不同,可以封装成一个函数. //得到参数的值 public static string GetParamVal(Document doc, Paramete ...
- [Winform]Media Player播放控制面板控制,单击事件截获
摘要 在项目中有这样的一个需求,需要在一台宣传机器上循环播放一段视频,并在体验的用户单击鼠标左键的时候推出全屏,可以让用户体验电脑的其它功能. 解决方案 考虑到都是windows系统的,所以采用了wi ...
- How to update WPF browser application manifest and xbap file with ‘mage.exe’
老外参考文章1 老外参考文章2 I created a WPF browser application MyApp then published it by ClickOnce in VS2008. ...