相关API的使用

本文介绍Guava工具库的Splitter、Joiner、CharMatcher功能,展示如何使用Java8进行统计摘要、查找最大最小值、转换集合为Map、分组及分区等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>16.0.1</version>
</dependency>

谷歌工具包:

@Test
public void testApi(){
    //拆分器
    String s="1,2,2,3,, ,";
    ArrayList<String> strings = Lists.newArrayList(Splitter.on(',').trimResults().omitEmptyStrings().split(s));
    System.out.println(strings);
    //连接器
    String s1 = Joiner.on(",").join(Lists.newArrayList("a","b","c"));
    System.out.println(s1);
    //字符匹配器
    String S2 = CharMatcher.JAVA_DIGIT.removeFrom("DFSD654ERASDF");
    System.out.println(S2);
}

JAVA8使用:

统计摘要:

ArrayList<Integer> list = Lists.newArrayList(1, 2, 3, 4);
IntSummaryStatistics st = list.stream().mapToInt((x)->x).summaryStatistics();
System.out.println(st.getAverage());
System.out.println(st.getCount());
System.out.println(st.getMin());
System.out.println(st.getSum());

最大最小值求和:

ArrayList<BigDecimal> list = Lists.newArrayList(new BigDecimal(0), new BigDecimal(1));
BigDecimal max = list.stream().max(Comparator.comparing(Function.identity())).orElse(BigDecimal.ZERO);
BigDecimal min = list.stream().min(Comparator.comparing(Function.identity())).orElse(BigDecimal.ZERO);
List<Integer> list = Lists.newArrayList(1,2,3,4);
Integer max = list.stream().reduce(Integer::max).orElse(0);
Integer min = list.stream().reduce(Integer::min).orElse(0);
Integer integer = list.stream().reduce(0, (a, b) -> a + b);
Car one = Car.builder().money(100).type("火车").build();
Car two = Car.builder().money(100).type("汽车").build();
Car three = Car.builder().money(200).type("卡车").build();
ArrayList<Car> list = Lists.newArrayList(one, two, three);
//list转mpa
Map<Integer, Car> map = list.stream().collect(Collectors.toMap(Car::getMoney, x -> x));
//按某个属性分组
Map<Integer, List<Car>> map1 = list.stream().collect(Collectors.groupingBy(Car::getMoney));
//按某个属性分组,并计算个数 也可以其他操作
Map<Integer, Long> map2 = list.stream().collect(Collectors.groupingBy(Car::getMoney, Collectors.counting()));
//按某个属性判断分区
Map<Boolean, List<Car>> map3 = list.stream().collect(Collectors.partitioningBy(x -> x.getMoney() > 100));
//排序
List<Car> list1 = list.stream().sorted(Comparator.comparingInt(Car::getMoney)).collect(toList());

分组获取最大最小值

Map<Integer, Optional<Car>> map4 = list.stream().collect(Collectors.groupingBy(Car::getMoney, Collectors.maxBy(Comparator.comparing(x -> x.getType().length()))));

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值