CollectionUtil:一个函数式风格的集合工具
本文分享一个函数式风格的集合操作工具。
使用示例
List<Integer> list = Arrays.asList(1, 2, 3, 4);
int size = CollectionUtil.size(list);//=> 4
boolean empty = CollectionUtil.isEmpty(list);//=> false
boolean notEmpty = CollectionUtil.isNotEmpty(list);//=> true
boolean indexValid = CollectionUtil.isIndexValid(list, 3);//=> true
boolean indexValid1 = CollectionUtil.isIndexValid(list, 4);//=> false
List<Object> list1 = CollectionUtil.list();//=> empty list
List<Integer> list2 = CollectionUtil.list(1);//=> (1)
List<Integer> list3 = CollectionUtil.list(list);//=> (1,2,3,4)
List<Integer> list4 = CollectionUtil.list(1, 2, 3, 4);//=> (1,2,3,4)
List<Integer> list5 = CollectionUtil.ensure(list);//=> list
List<Integer> list6 = CollectionUtil.ensure((List<Integer>) null);//=> empty list
Map<String, Integer> map = CollectionUtil.ensure(Collections.singletonMap("one", 1));//=> map contains: one - 1
Map<String, Integer> map1 = CollectionUtil.ensure((Map<String, Integer>) null);//=> empty map
Set<Integer> set = CollectionUtil.ensure(new HashSet<>(list));//=> set contains: 1,2,3,4
Set<Integer> set1 = CollectionUtil.ensure((Set<Integer>) null);//=> empty set
List<Integer> copyList = CollectionUtil.copy(list);//=> (1,2,3,4)
Integer head = CollectionUtil.head(list);//=> 1
List<Integer> tailList = CollectionUtil.tail(list);//=> (2,3,4)
List<Integer> list7 = CollectionUtil.append(list, 0);//=> (1,2,3,4,0)
CollectionUtil.forEach(list, i -> System.out.println("int:" + i));
List<Integer> reversedList = CollectionUtil.reverse(list);//=> (4,3,2,1)
List<Integer> rangeList = CollectionUtil.range(1, 5);//=> (1,2,3,4)
Integer integer1 = CollectionUtil.find(list, i -> i % 2 == 0, -1);//=> 2
Integer integer2 = CollectionUtil.find(list, i -> i > 10, -1);//=> -1
int count = CollectionUtil.count(list, i -> i % 2 == 0);//=> 2
boolean contains = CollectionUtil.contains(list, i -> i % 2 == 0);//=> true
List<Integer> concatList = CollectionUtil.concat(list,
Arrays.asList(11, 22),
Arrays.asList(33, 44));//=> (1,2,3,4,11,22,33,44)
CollectionUtil.doTimes(3, i -> {
System.out.print("(" + i + ")");
});//打印 (0) (1) (2)
List<Integer> list8 = CollectionUtil.doTimes(5, i -> {
return i * i;
});//=> (0,1,4,9,16)
List<Integer> filteredList = CollectionUtil.filter(list, i -> i % 2 == 0);//=> (2,4)
String reducedStr = CollectionUtil
.reduce(list, new StringBuilder(),
(builder, integer) -> builder.append('(').append(integer).append(')'))
.toString();//=> "(1)(2)(3)(4)"
List<Integer> list9 = CollectionUtil.map(list, i -> i * 10);//=> (10,20,30,40)
List<String> list10 = CollectionUtil.map(
Arrays.asList(1, 2, 3, 4),
Arrays.asList("one", "two", "three", "four"),
i -> s -> s + ":" + i);//=> ("one:1","two:2","three:3","four:4")
完整实现
import java.util.*;
import java.util.function.BiFunction

本文介绍了一个名为CollectionUtil的Java工具类,它提供了诸如大小、空判断、索引验证、创建列表、集合操作等功能,以函数式编程风格简化集合处理。
最低0.47元/天 解锁文章
1502

被折叠的 条评论
为什么被折叠?



