对Java8流处理和guava使用的一些小技巧

package com.gftech.cloud; import com.gftech.cloud.exceptions.ProductError; import com.google.common.base.*; import com.google.common.collect.*; import com.google.common.primitives.Ints; import com.sinsz.c.exception.SystemException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Nullable; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.google.common.collect.ImmutableList.of;

【对Java8流处理和guava使用的一些小技巧】/**
  • @author xxx
  • @date 2018/9/6 9:50
    */
@RunWith(SpringRunner.class) @SpringBootTest public class TestGuava {@Test public void test() { Stream stream1 = Stream.iterate(10, n -> n + 2).limit(3); Stream stream2 = Stream.generate(() -> UUID.randomUUID().toString()).limit(3); Stream.concat(stream1, stream2).forEach(System.out::println); //拼接两个流List list = Arrays.asList(1, 2, 3, 4, 5); Instant start = Instant.now(); //时间戳 Stream stream = list.stream(); //串行流 Instant end = Instant.now(); System.out.println(Duration.between(start, end).getSeconds()); Instant start1 = Instant.now(); Stream parallelStream = list.parallelStream(); //并行流 Instant end1 = Instant.now(); System.out.println(Duration.between(start1, end1).getSeconds()); List strList = Stream.iterate("1", n -> n + "2").limit(10).collect(Collectors.toList()); strList.stream().mapToInt(Integer::valueOf).forEach(System.out::println); //转换流为数字类型 strList.stream().map(StringBuilder::new).collect(Collectors.joining(",")); //转换流为字符串类型,按照joining收集器的条件拼接 Stream stream = Stream.of("i", "love", "programing"); stream.flatMap(c -> Stream.of(c.split(""))).forEach(System.out::println); //拆分流内容 stream.filter(c -> c.contains("o")).forEach(System.out::println); //筛选掉流中不符合条件的 boolean b1 = stream.anyMatch(String::isEmpty); //部分符合条件返回真 boolean b2 = stream.allMatch(String::isEmpty); //全部符合条件返回真 boolean b3 = stream.noneMatch(String::isEmpty); //全部不符合条件返回真Stream integers = Stream.of(1, 2, 3, 4, 5, 5, 4, 3, 2, 1); Integer sum = integers.reduce(0, (m, n) -> m + n); //计算数字流 Integer integer = integers.distinct().sorted(Integer::compareTo).reduce(0, (m, n) -> m + n); //去重排序计算数字流 integers.distinct().sorted(Comparator.reverseOrder()).forEach(System.out::println); //倒序排序Function before = n -> n + 10; Function after = n -> n * n; Integer integer = before.andThen(after).apply(10); //先执行before,在执行after Integer integer1 = before.compose(after).apply(10); //先执行after,在执行before Integer integer2 = before.apply(10); Integer integer3 = after.apply(10); Predicate predicate = str -> str.equals("miao"); Predicate predicate1 = str -> str.startsWith("m"); boolean b = predicate.test("m"); //满足条件返回真 boolean b1 = predicate.and(predicate1).test("m"); //predicate和predicate1满足条件返回真 boolean b2 = predicate.negate().test("xxx"); //不满足条件返回真 boolean b3 = predicate.or(predicate1).test("m"); //predicate或者predicate1满足条件返回真StringBuilder sb = new StringBuilder(); Joiner.on("-").skipNulls().appendTo(sb, "1", "2"); //谷歌拼接字符串,为空的=不拼接 Joiner.on("-").useForNull("noon").appendTo(sb, null, 1); //谷歌拼接字符串,为空的=noon,继续拼接String str = "a, , b, , c, , d"; Splitter.on(",").trimResults().omitEmptyStrings().split(str).forEach(System.out::println); //谷歌去空去空字符串分隔字符串、List list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); Multiset multiset = LinkedHashMultiset.create(list); multiset.setCount("e", 10); //添加或者删除e,个数补充到10个 Integer integer = multiset.count("e"); //计数e的次数 Integer integer1 = multiset.elementSet().size(); //集合去重后计算个数 multiset.clear(); //集合清空 Integer integer2 = multiset.size(); //如果你想防止出现键值对,可以用HashMultimap;如果你需要键值对按照自然顺序排列,你可以使用TreeMultimap;甚至你想按插入顺序来遍历集合,LinkedHashMultimap可以满足你的需求 Multimap multimap = HashMultimap.create(); multimap.put("a", 1); multimap.put("a", 2); multimap.put("a", 3); Collection collection = multimap.get("a"); //将key为a的map转成数组 List list = new ArrayList<>(collection); //将数组转换成List集合 Map> map = multimap.asMap(); //将multimap转换成Map(这个map可能是一对多的) Integer integer = multimap.keySet().size(); //去重计算key的个数List together = Stream.of(Arrays.asList(1, 2, 3, 4), Arrays.asList(5, 6, 7, 8)) .flatMap(Collection::stream).collect(Collectors.toList()); //flatmap将流扁平化,对流进行各种操作 List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); boolean b = Arrays.equals(list.toArray(), together.toArray()); String str = CharMatcher.digit().retainFrom("wangxiaoying123"); //获取字符串中的数字 String s = CharMatcher.digit().removeFrom("wangxiaoying123"); //获取字符串中的字母 String s1 = "f,ff,fff,,o,oo,,,ooo"; Iterable iterable = Splitter.on(",").omitEmptyStrings().trimResults().split(s1); //分隔字符串,连续出现的分隔符去重int[] array = {1, 2, 3, 4, 5, 6}; boolean boo = Ints.contains(array, 4); int indexOf = Ints.indexOf(array, 4); int max = Ints.max(array); int min = Ints.min(array); int[] array1 = {7, 8, 9, 0}; int[] cancat = Ints.concat(array, array1); Map map = new HashMap<>(); map.put("1", 1); map.put("2", 2); Map changeMap = Maps.transformValues(map, new Function() {//对map中每一个key对应的value值进行操作,function就是从一个对象到另外一个对象的转换变形 double d = 1.10; @Nullable @Override public Object apply(@Nullable Object input) { Integer i = (Integer) input; return d * i; } }); Map map1 = new HashMap<>(); map1.put("map1", "map1"); map1.put("map2", "map2"); Map map2 = new HashMap<>(); map2.put("map1", "map2"); map2.put("map2", "map2"); MapDifference mapDifference = Maps.difference(map1, map2); //map集合的比较 boolean b = mapDifference.areEqual(); //是否完全一致,包括键和值 Map m1 = mapDifference.entriesOnlyOnLeft(); //键只存在于左边Map的映射项 Map m2 = mapDifference.entriesOnlyOnRight(); //键只存在于右边Map的映射项 Map m3 = mapDifference.entriesDiffering(); //键相同但是值不同值映射项 Map m4 = mapDifference.entriesInCommon(); //两个Map中都有的映射项,包括匹配的键与值String s = Preconditions.checkNotNull(null, new SystemException(ProductError.APP_DOCTOR_ERROR_020)); //对象为空时显示指定的错误信息List list = Arrays.asList("1","2","3","4","5","6","7"); List partition = Lists.partition(list, 2); //Guava对集合进行分页分条数 ImmutableList immutablePeople = copyOf(existingPeople); //Guava将集合转成不变集合 List list = of(); //初始化集合为不变集合BiMap upperToSmall = HashBiMap.create(); upperToSmall.put("A", "a"); upperToSmall.put("B", "b"); upperToSmall.put("C", "c"); BiMap smallToUpper = upperToSmall.inverse(); //BiMap可以使map中的键值反转,这是一个视图,这意味着,在对反转后的map中的任何增删改操作都会影响原来的map //BiMap.forcePut(key, value)来实现重复添加value的方法NutMap map = new NutMap(); //Mutmap获取key值指定其value值类型,简化一次类型转换 map.put("name", "bushi"); map.put("age", 63); map.put("sex", true); map.put("time", new Date()); System.out.println(map.getString("name")); System.out.println(map.getInt("age")); System.out.println(map.getBoolean("sex")); System.out.println(map.getTime("time")); BigDecimal fee = new BigDecimal(priceL).divide(new BigDecimal(1), 2, BigDecimal.ROUND_HALF_UP); 计算小数,四舍五入 DecimalFormat df=new DecimalFormat("###,###"); //数字格式化 System.out.println("这是我的输出"); } }/** * 对Stream流里面的元素去重 */ public static Predicate distinctByKey(Function keyExtractor) { Map seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; }

flatMap的stream运行流程.png

    推荐阅读