Java 8 Lambda 学习笔记
来源:互联网 发布:最早的程序员 编辑:程序博客网 时间:2024/06/05 11:44
本笔记主要是根据leveluplunch的博客整理的关于Java 8 lambda的知识。
1、统计汇总
DoubleSummaryStatistics stats = companies.stream().mapToDouble((x) -> x.getRevenue()).summaryStatistics();DoubleSummaryStatistics stats = companies.stream().collect(Collectors.summarizingDouble(Company::getRevenue));
2、Optional使用
// ofNullable和orElse使用Optional<Framework> nullOptional = Optional.ofNullable(null);Framework orElseFramework = nullOptional.orElse(framework);// orElseGet/orElseThrow使用List<String> carsFiltered = Optional.ofNullable(cars) .orElseGet(Collections::emptyList) .stream() .filter(Objects::nonNull) .collect(Collectors.toList());// 级联调用,避免空指针Optional.of(new Outer()) .map(Outer::getNested) .map(Nested::getInner) .map(Inner::getFoo) .ifPresent(System.out::println);// 或者利用SupplierOuter obj = new Outer();resolve(() -> obj.getNested().getInner().getFoo()); .ifPresent(System.out::println);public static <T> Optional<T> resolve(Supplier<T> resolver) { try { T result = resolver.get(); return Optional.ofNullable(result); } catch (NullPointerException e) { return Optional.empty(); }}
3、Function
Function<Person, Job> mapPersonToJob = new Function<Person, Job>() { public Job apply(Person person) { Job job = new Job(person.getPersonId(), person.getJobDescription()); return job; }};List<Person> persons = Lists.newArrayList(new Person(1, "Husband"), new Person(2, "Dad"), new Person(3, "Software engineer"), new Person(4, "Adjunct instructor"), new Person(5, "Pepperoni hanger"));// Map a list of objectsList<Job> jobs = persons.stream().map(mapPersonToJob).collect(Collectors.toList());// Map object to objectPerson person = new Person(1, "Description");Job job = mapPersonToJob.apply(person);
4、Predicate
Predicate<String> hasLengthOf10 = new Predicate<String>() { @Override public boolean test(String t) { return t.length() > 10; }};boolean outcome = hasLengthOf10.test(randomString);Predicate<String> nonNullPredicate = Objects::nonNull;Predicate<String> containsLetterA = p -> p.contains("A");boolean outcome = hasLengthOf10.or(containsLetterA).test(containsA);public static <T> Predicate<T> or (Predicate<T> ... predicates){ return Stream.of(predicates).reduce(Predicate::or).get();}public static <T> Predicate<T> and (Predicate<T> ... predicates){ return Stream.of(predicates).reduce(Predicate::and).get();}
5、构建stream
Stream<String> stream = Stream.of("java 8 ", "leveluplunch.com", "examples", "exercises");// stream to String String joined = stream.map(String::trim).collect(Collectors.joining(","));int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };// array to streamint sum = Arrays.stream(numbers).sum();// 统计单词个数long uniqueWords = java.nio.file.Files .lines(Paths.get("word-occurrences-in-file.txt"), Charset.defaultCharset()) .flatMap(line -> Arrays.stream(line.split(" ."))).distinct() .count();// iterateStream.iterate(0, n -> n + 3).limit(10).forEach(System.out::println);// generateStream.generate(Math::random).limit(10).forEach(System.out::println);// 产生随机字符串列表Stream.generate(()-> RandomStringUtils.randomAlphabetic(25)).limit(size).collect(Collectors.toList());// 拼接streamStream<String> stream1 = Stream.of("one", "two");Stream<String> stream2 = Stream.of("three", "four");Stream.concat(stream1, stream2).forEach(e -> System.out.println(e));IntStream intStream1 = IntStream.of(1, 2);IntStream intStream2 = IntStream.of(3, 4);IntStream.concat(intStream1, intStream2).forEach(e -> System.out.println(e));int val = IntStream.concat(intStream1, intStream2).distinct().sum();OptionalInt sum2 = IntStream.concat(intStream1, intStream2).distinct().reduce((a, b) -> a + b);
6、stream 转换为其他结构
// stream to ListList<String> abc = Stream.of("a", "b", "c").collect(Collectors.toList());// stream to MapMap<String, Item> map = items.stream().collect(Collectors.toMap(Item::getKey, item -> item));// stream to SetSet<Integer> numbers = Stream.of(1, 2, 3).collect(Collectors.toSet());// stream to StringString streamToString = Stream.of("a", "b", "c").collect(Collectors.joining());// stream to arrayString[] stringArray = Stream.of("One", "Two", "Three").toArray(String[]::new);Integer[] stringArray = Stream.of(1, 2, 3).toArray(Integer[]::new);int[] intArray = IntStream.of(1, 2, 3).toArray();// flatten List<List<Object>>List<List<Object>> list = ...;List<Object> flat = list.stream().flatMap(List::stream).collect(Collectors.toList());
7、IntStream
int sum = IntStream.builder().add(10).add(10).build().sum();IntStream first = IntStream.builder().add(10).build();IntStream second = IntStream.builder().add(10).build();// concatIntStream third = IntStream.concat(first, second);// generateOptionalInt one = IntStream.generate(() -> 1).limit(10).distinct().findFirst();// iterateList<Integer> numbers = IntStream.iterate(0, n -> n + 3).limit(3).boxed().collect(Collectors.toList());// rangeList<Integer> numbers = IntStream.range(1, 3).boxed().collect(Collectors.toList());List<Integer> numbers = IntStream.rangeClosed(1, 3).boxed().collect(Collectors.toList());List<String> integers = new ArrayList<String>();integers.add("1");integers.add("2");integers.add("3");OptionalInt intStream = integers.stream().mapToInt(Integer::parseInt).max();int[] numbers = { 1, 2, 3, 4, 5, 6 };List<Integer> listOfInteger = Arrays.stream(numbers).boxed().collect(Collectors.toList());
8、Stream find/match
List<HiddenObjectGame> games;boolean containVowel = games.stream().allMatch(game -> game.getName().contains("a"));boolean playsGt1000 = games.stream().anyMatch(game -> game.getTotalPlays() > 1000);Predicate<HiddenObjectGame> playsGt1000 = p -> p.getTotalPlays() > 1000;Predicate<HiddenObjectGame> ratingGt5 = p -> p.getRating() > 5;boolean noneMatch = games.stream().noneMatch(ratingGt5.and(playsGt1000));Optional<HiddenObjectGame> firstHiddenGame = games.stream().findFirst();Predicate<HiddenObjectGame> releaseDateInApril = p -> Month.APRIL == p.getReleaseDate().getMonth();Optional<HiddenObjectGame> hiddenGameReleaseInApril = games.stream().filter(releaseDateInApril).findAny();
9、Stream filter
List<Post> postWithLessThan500 = posts.stream() .filter(p -> p.wordlength < 500).collect(Collectors.toList());List<String> tags = posts .stream() .map(Post::getTags) .flatMap(tag -> Arrays.stream(tag.split(",")).map(String::trim).map(String::toLowerCase)) .map(Object::toString) .distinct() .collect(Collectors.toList()); List<Post> firstTwoPosts = posts.stream().limit(2).collect(Collectors.toList());
10、Stream reduce
List<Precipitation> precip;double totalPrecipYear = precip.stream().mapToDouble(Precipitation::getAmount).sum();OptionalDouble totalPrecipYear2 = precip.stream() .mapToDouble(Precipitation::getAmount).reduce(Double::sum);double totalPrecipYear3 = precip.stream() .mapToDouble(Precipitation::getAmount).reduce(0, (a, b) -> a + b);Optional<String> optionalJava = Stream.of("a", "b", "c").reduce((a, b) -> b);String lastValue = Stream.of("a", "b", "c").reduce((a, b) -> b).orElse("false");
11、List 转换为原生数组
List<Double> searchEngineMarketShare = Lists.newArrayList();double [] searchEngineMarketShareArray = searchEngineMarketShare .stream() .mapToDouble(Double::doubleValue) .toArray();
12、过滤空值
Stream<String> language = Stream.of("java", "python", "node", null, "ruby", null, "php");List<String> result = language.filter(x -> x!=null).collect(Collectors.toList());result.forEach(System.out::println);List<String> result = language.filter(Objects::nonNull).collect(Collectors.toList());
13、对Map value排序
unsortMap.entrySet().stream() .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));public static <K, V extends Comparable<? super V>> Map<K, V> compareByValue(Map<K, V> map) { Map<K, V> result = new LinkedHashMap<>(); Stream<Map.Entry<K, V>> mapInStream = map.entrySet().stream(); mapInStream.sorted(Map.Entry.comparingByValue()) .forEachOrdered(x -> result.put(x.getKey(), x.getValue())); return result;}
14、groupBy/count
List<String> items = Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya");Map<String, Long> result = items.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));Map<String, Long> counting = items.stream().collect(Collectors.groupingBy(Item::getName, Collectors.counting()));Map<String, Integer> sum = items.stream().collect(Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getQty))); Map<String,List<Person>> personByCity = people.stream().collect(Collectors.groupingBy(Person::getCity));
15、对集合排序Comparator
Collections.sort(listDevs, new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getName().compareTo(o2.getName()); }});listDevs.sort((Developer o1, Developer o2)->o1.getName().compareTo(o2.getName()));listDevs.sort((o1, o2)->o1.getName().compareTo(o2.getName()));
16、CompletableFuture操作
// 构造CompletableFuture对象(runAsync或者supplyAsync)CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> longTask(param));CompletableFuture<Void> runAsync = CompletableFuture.runAsync(() -> System.out.println("running async task"), service);// 变换CompletableFuture异步获取的数据(thenApply或者thenApplyAsync)CompletableFuture<Double> f = CompletableFuture.supplyAsync(() -> "4") .thenApply(Integer::parseInt) .thenApply(r -> r * r * Math.PI);// 对异步结果进行串联(thenCompose)// thenCombine是并联起两个独立的futureOptional<List<Integer>> op;CompletableFuture<Long> f = CompletableFuture.supplyAsync(() -> longTask(1000000)) .thenComposeAsync( CompletableFuture.supplyAsync(() -> op.get().stream().map(Integer::toUnsignedLong).reduce(0L, (x, y) -> x + y)));// 任务之间的衔接CompletableFuture<String> taskUsingCache = CompletableFuture.supplyAsync(simulatedTask(1,map.get("key")),service);CompletableFuture<Void> acceptingTask = taskUsingCache.thenAccept(list::add); // 将taskUsingCache的结果加入到ListCompletableFuture<Void> cleanUp = taskUsingCache.thenRunAsync(map::clear,service); // taskUsingCache结束之后清空map// 两个任务中第一个完成即可CompletableFuture<String> callingCompletable = CompletableFuture.supplyAsync(simulatedTask(2, "calling"), service);CompletableFuture<String> nestedCompletable = CompletableFuture.supplyAsync(simulatedTask(1, "nested"), service);CompletableFuture<Void> collector = callingCompletable.acceptEither(nestedCompletable, results::add);// CompletableFuture<Void> finisher = run1.runAfterEitherAsync(run2,() -> results.add(results.get(0).toUpperCase()),service);// 综合示例public static <V> CompletableFuture<List<V>> allOf(Collection<? extends CompletableFuture<? extends V>> futures) { return CompletableFuture .allOf(futures.toArray(new CompletableFuture[futures.size()])) .thenApply(v -> futures.stream() .map(CompletableFuture::join) .collect(Collectors.<T>toList()) );}public static List<PriceRecord> findPricesCustomExecutor() { List<CompletableFuture<PriceRecord>> futures = shops.stream() .map(s -> CompletableFuture.supplyAsync(s::getPrice, es)) .map(f -> f.thenCompose(p -> CompletableFuture.supplyAsync(() -> Discount.applyDiscount(p), es))) .collect(toList()); return futures.stream() .map(CompletableFuture::join) .collect(toList());}
17、CompletableFuture优雅处理异常
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("failAfter-%d").build());public static <T> CompletableFuture<T> failAfter(Duration duration) { final CompletableFuture<T> promise = new CompletableFuture<>(); scheduler.schedule(() -> { final TimeoutException ex = new TimeoutException("Timeout after " + duration); return promise.completeExceptionally(ex); }, duration.toMillis(), MILLISECONDS); return promise;}public static <T> CompletableFuture<T> within(CompletableFuture<T> future, Duration duration) { final CompletableFuture<T> timeout = failAfter(duration); return future.applyToEither(timeout, Function.identity());}final CompletableFuture<Response> responseFuture = within(asyncCode(), Duration.ofSeconds(1));responseFuture.thenAccept(this::send) .exceptionally(throwable -> { log.error("Unrecoverable error", throwable); return null; });
18、对Map优雅操作
Map<Integer, String> map = new HashMap<>();for (int i = 0; i < 10; i++) { map.putIfAbsent(i, "val" + i);}map.forEach((id, val) -> System.out.println(val));map.getOrDefault(42, "not found");
19、获取最大日期的对象
Contact lastContact = Collections.max(contacts, Comparator.comparing(c -> c.lastUpdated));
1 0
- Java 8 Lambda 学习笔记
- java lambda 学习笔记
- Java 8 Lambda 学习笔记(一)
- JAVA SE 8 学习笔记(一)lambda表达式
- JAVA SE 8 学习笔记(三)使用lambda编程
- java lambda表达式 闭包学习笔记
- Java学习笔记——Lambda表达式
- java 8 lambda 表达式 学习
- Java 8 Lambda Expression 学习
- 学习笔记8-python-lambda&map
- Lambda 学习笔记 杂感
- boost::lambda学习笔记
- Lambda表达式学习笔记
- lambda学习笔记
- Lambda演算学习笔记
- Lambda学习笔记
- pyhon学习笔记--lambda
- 【Java学习笔记之三十一】详解Java8 lambda表达式
- 【mfc】_pFirstBlock==pHead解决办法
- 洛谷 P1186 玛丽卡
- poj 1743 Musical Theme(后缀数组+二分答案+height数组分组)
- CentOS 7 安装Memcached服务
- epub转换mobi
- Java 8 Lambda 学习笔记
- 【DP】【分队问题】
- noip2014联合权值 (贪心+数学推导)
- 转载博文:Centos 下打造合适的科研环境
- 【NOIP 模拟题】[T2]分解数(线性筛+贪心)
- 浅谈 easyui tabs 的href和content属性
- windows下python装openpyxl 以及jdcal
- 剑指offer面试题14
- SpringMVC参数绑定注解