!819 添加filltering

Merge pull request !819 from MiratowA/v6-dev
This commit is contained in:
Looly
2022-09-26 04:06:19 +00:00
committed by Gitee
2 changed files with 53 additions and 20 deletions

View File

@@ -20,50 +20,62 @@ public class CollectorUtilTest {
@Test
public void reduceListMapTest() {
final Set<Map<String, Integer>> nameScoreMapList = StreamUtil.of(
// 集合内的第一个map包含两个key value
MapUtil.builder("苏格拉底", 1).put("特拉叙马霍斯", 3).build(),
MapUtil.of("苏格拉底", 2),
MapUtil.of("特拉叙马霍斯", 1),
MapUtil.of("特拉叙马霍斯", 2)
// 集合内的第一个map包含两个key value
MapUtil.builder("苏格拉底", 1).put("特拉叙马霍斯", 3).build(),
MapUtil.of("苏格拉底", 2),
MapUtil.of("特拉叙马霍斯", 1),
MapUtil.of("特拉叙马霍斯", 2)
).collect(Collectors.toSet());
// 执行聚合
final Map<String, List<Integer>> nameScoresMap = nameScoreMapList.stream().collect(CollectorUtil.reduceListMap());
Assert.assertEquals(MapUtil.builder("苏格拉底", Arrays.asList(1, 2))
.put("特拉叙马霍斯", Arrays.asList(3, 1, 2)).build(),
nameScoresMap);
.put("特拉叙马霍斯", Arrays.asList(3, 1, 2)).build(),
nameScoresMap);
}
@Test
public void testTransform() {
Stream<Integer> stream = Stream.of(1, 2, 3, 4)
.collect(CollectorUtil.transform(EasyStream::of));
.collect(CollectorUtil.transform(EasyStream::of));
Assert.assertEquals(EasyStream.class, stream.getClass());
stream = Stream.of(1, 2, 3, 4)
.collect(CollectorUtil.transform(HashSet::new, EasyStream::of));
.collect(CollectorUtil.transform(HashSet::new, EasyStream::of));
Assert.assertEquals(EasyStream.class, stream.getClass());
}
@Test
public void testToEasyStream() {
final Stream<Integer> stream =Stream.of(1, 2, 3, 4)
.collect(CollectorUtil.toEasyStream());
final Stream<Integer> stream = Stream.of(1, 2, 3, 4)
.collect(CollectorUtil.toEasyStream());
Assert.assertEquals(EasyStream.class, stream.getClass());
}
@Test
public void testToEntryStream() {
final Map<String, Integer> map = Stream.of(1, 2, 3, 4, 5)
// 转为EntryStream
.collect(CollectorUtil.toEntryStream(Function.identity(), String::valueOf))
// 过滤偶数
.filterByKey(k -> (k & 1) == 1)
.inverse()
.toMap();
Assert.assertEquals((Integer)1, map.get("1"));
Assert.assertEquals((Integer)3, map.get("3"));
Assert.assertEquals((Integer)5, map.get("5"));
// 转为EntryStream
.collect(CollectorUtil.toEntryStream(Function.identity(), String::valueOf))
// 过滤偶数
.filterByKey(k -> (k & 1) == 1)
.inverse()
.toMap();
Assert.assertEquals((Integer) 1, map.get("1"));
Assert.assertEquals((Integer) 3, map.get("3"));
Assert.assertEquals((Integer) 5, map.get("5"));
}
@Test
public void testFiltering() {
final Map<Integer, Long> map = Stream.of(1, 2, 3)
.collect(Collectors.groupingBy(Function.identity(),
CollectorUtil.filtering(i -> i > 1, Collectors.counting())
));
Assert.assertEquals(MapUtil.builder()
.put(1, 0L)
.put(2, 1L)
.put(3, 1L)
.build(), map);
}
}