将字符串集合转换为Integer集合
Lists.transform可以很方便将一个集合转换成另外一种类型的集合。
List<String> listStr = Lists.newArrayList("1", "2", "3"); //将字符串集合转换为Integer集合 List<Integer> listInteger = Lists.transform(listStr, new Function<String, Integer>() {
@Nullable
@Override
public Integer apply(@Nullable String s)
{ return Integer.valueOf(s); }
});
在Java 8中的实现为
List<Integer> listInteger2 = listStr.stream().map(Integer::valueOf).collect(Collectors.toList());
Iterables.find查找集合首个匹配的元素
List<String> listStr = Lists.newArrayList("hello", "world", "hehe"); //查找首个以h开头的值 String value = Iterables.find(listStr, new Predicate<String>() { @Override public boolean apply(String input) { return input.startsWith("h"); } });
在Java 8中的实现为
String value2 = listStr.stream().findFirst().filter(input -> input.startsWith("h")).get();
Collections2.filter过滤集合中所有符合特定条件的元素。
List<String> listWithH = Lists.newArrayList(Collections2.filter(listStr, new Predicate<String>() { @Override public boolean apply(@Nullable String s) { return s.startsWith("h"); } }));
在Java 8中的实现为
List<String> listWithH2 = listStr.stream().filter(input -> input.startsWith("h")).collect(Collectors.toList());
Lists.partition可以将一个大的集合分割成小集合,适用于分批查询、插入等场景。
List listStr = Lists.newArrayList(“1”, “2”, “3”,“4”,“5”,“6”,“7”);
List<List<String>> batchList = Lists.partition(listStr,3);
//被分割成了: [[1, 2, 3], [4, 5, 6], [7]]