java8的reduce方法

在 Java 8 中,reduce 是一个流操作方法,用于将流中的元素按照指定的操作进行归约(reduce)操作,最终得到一个结果。

reduce 方法有三种重载形式:

  1. T reduce(T identity, BinaryOperator<T> accumulator)
    这个方法接受一个初始值 identity 和一个二元操作符 accumulator。它使用初始值和流中的元素依次进行二元操作,将结果累积到最终的结果中,并返回最终结果。

  2. <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)
    这个方法接受一个初始值 identity、一个累加器函数 accumulator 和一个组合器函数 combiner。它与第一种形式的 reduce 方法类似,但是可以用于并行流的归约操作。在并行流中,流被分成多个子流并行处理,然后使用组合器函数将各个子流的结果合并成最终结果。

  3. Optional<T> reduce(BinaryOperator<T> accumulator)
    这个方法只接受一个二元操作符 accumulator,它没有初始值。它将流中的元素依次进行二元操作,最终返回一个 Optional 对象,表示可能存在的结果。

reduce 方法的使用可以实现多种操作,例如对流中的元素求和、求最大值、求最小值等。下面是一些示例用法:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// 求和(首次运行前认为a=0,b为第1个元素,第二次运行前a=0+b(上一轮结果),b为第2个元素,依次类推得到结果15)
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
System.out.println(sum); // 输出: 15

// 求最大值
Optional<Integer> max = numbers.stream().reduce(Integer::max);
max.ifPresent(System.out::println); // 输出: 5

// 求乘积(首次运行前认为a=第1个元素,b为第2个元素,第二次运行前a=元素1*元素2(上一轮结果),b为第3个元素)
Optional<Integer> product = numbers.stream().reduce((a, b) -> a * b);
product.ifPresent(System.out::println); // 输出: 120

// 表达式return方式
User1 user1 = new User1(1,"1");
User1 user2 = new User1(2,"2");
User1 user3 = new User1(3,"3");
User1 user4 = new User1(4,"4");
User1 user5 = new User1(5,"5");

List<User1> user1List = Lists.newArrayList();
List<User1> user2List = Lists.newArrayList();

user1List.add(user1);
user1List.add(user2);
user1List.add(user3);
user1List.add(user4);
user1List.add(user5);

final AtomicInteger index = new AtomicInteger(0);
user1List.stream().reduce((a,b)->{
    System.out.println("第"+ (index.getAndAdd(1)) +"轮开始");
    System.out.println("a---->"+JSON.toJSONString(a));
    System.out.println("b---->"+JSON.toJSONString(b));

    User1 user11 = new User1();
    user11.setHigh(a.getHigh()+b.getHigh());
    System.out.println("user11---->"+JSON.toJSONString(user11));
    System.out.println("第"+ (index.get()) +"轮结束");
    System.out.println();

    return user11;
}).ifPresent(user2List::add);

System.out.println("user2List---->"+JSON.toJSONString(user2List));

--输出
第0轮开始
a---->{"high":1,"name":"1"}
b---->{"high":2,"name":"2"}
user11---->{"high":3,"name":"1"}
第1轮结束

第1轮开始
a---->{"high":3,"name":"1"}
b---->{"high":3,"name":"3"}
user11---->{"high":6,"name":"1"}
第2轮结束

第2轮开始
a---->{"high":6,"name":"1"}
b---->{"high":4,"name":"4"}
user11---->{"high":10,"name":"1"}
第3轮结束

第3轮开始
a---->{"high":10,"name":"1"}
b---->{"high":5,"name":"5"}
user11---->{"high":15,"name":"1"}
第4轮结束

user2List---->[{"high":15,"name":"1"}]

从结果可以看到每次的return都作为下一轮的初始值。

在这些示例中,reduce 方法根据提供的操作符对流中的元素进行归约操作,得到最终的结果。注意,reduce 方法返回的结果可能是一个 Optional 对象,因为流中可能没有元素或者操作过程中产生了空值。因此,你可以使用 Optional 的方法来处理可能为空的结果。

以下是更多的示例用法:

List<String> words = Arrays.asList("Hello", "World", "Java", "Programming");

// 拼接字符串
String concatenated = words.stream().reduce("", (a, b) -> a + " " + b);
System.out.println(concatenated); // 输出: " Hello World Java Programming"

// 求字符串列表中最长的单词
Optional<String> longestWord = words.stream().reduce((a, b) -> a.length() > b.length() ? a : b);
longestWord.ifPresent(System.out::println); // 输出: "Programming"

// 检查是否存在以大写字母开头的单词
boolean hasUpperCase = words.stream().anyMatch(s -> Character.isUpperCase(s.charAt(0)));
System.out.println(hasUpperCase); // 输出: true

// 计算数字列表的平均值
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
double average = numbers.stream().mapToDouble(Integer::doubleValue).average().orElse(0);
System.out.println(average); // 输出: 3.0

// 连接两个字符串列表
List<String> list1 = Arrays.asList("Hello", "World");
List<String> list2 = Arrays.asList("Java", "Programming");
List<String> combined = Stream.concat(list1.stream(), list2.stream()).collect(Collectors.toList());
System.out.println(combined); // 输出: ["Hello", "World", "Java", "Programming"]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PassMark imageUSB V1.1 Copyright (C) 2013 PassMark Software All Rights Reserved http://www.passmark.com Overview ======== ImageUSB is a free utility which lets you write an image concurrently to multiple USB Flash Drives. Capable of creating exact bit-level copies of USB Flash Drive (UFDs), ImageUSB is an extremely effective tool for the mass duplication of UFDs. Unlike other USB duplication tools, ImageUSB can preserve all unused and slack space during the cloning process, including the Master Boot Record (MBR). ImageUSB can perform flawless mass duplications of all UFD images, including bootable UFDs. Note: imageUSB is currently only able to handle images (.bin) files that were created by imageUSB. Running this software to write an image file will destroy any data on any removable drive volume specified. To install imageUSB =================== Copy the imageUSB directory to the Program Files directory. To uninstall imageUSB ===================== Delete the directory to the Program Files directory. Requirements ============ - Operating System: XP, Vista, Windows 7 - RAM: 256 Meg - Disk space: 2MB free hard disk space, plus any additional space required to store image file. Usage ===== 1) Before starting: Backup the USB Flash Drive contents to a hard disk drive. This process will overwrite the USB drive selected, so remove any other removable drives on the system to reduce the likelihood of mistakes. 2) This program requires Adminstration Privileges.. 3) Follow the instructions on screen or in the Help documentation provided. Be very careful to select the correct drive letter!!! Version History =============== Here is a summary of all changes that have been made in each version of imageUSB. Release 1.1.1012 WIN32 release 16 Oct 2013 - Write verification is now supported for images not created with imageUSB. A checksum will be calculated for the image and then compared to the image written on the UFD. - Enabled UFD list while imageUSB is writing/creating images. Should allow you to scroll the list to see progress of all UFD when more than 4 drives are used. - Source code clean up Release 1.1.1011 WIN32 release 18 March 2013 - Added ability to select '.img' files. Release 1.1.1010 WIN32 release 22 October 2012 -Fixed a program crash when reading fake USB drives. It seems that some USB flash drives are tricking the Windows API to incorrectly recognizing the end of the drive. Release 1.1.1009 WIN32 release 9 July 2012 -Allows writing images larger than destination drives. End of the image will be truncated and not be written to the drive. Release 1.1.1008 WIN32 release 19 January 2012 -Added a delay on retry for failed write attempts. Will wait 1 sec before retry. -Address an issue where writing image would sometimes fail with Error 5: Access is Denied. Release 1.1.1007 WIN32 release 16 November 2011 -Fixed some erroneous debug logging messages. -Tweaked verification settings, should report which offset verification failed at. -For Writing to flash drive, upon write failure, imageUSB will retry up to 3 times to rewrite to the failed location. Release 1.1.1006 WIN32 release 6 October 2011 -Improved debug logging. Release 1.1.1005 WIN32 release 6 July 2011 - Added the ability to write .ISO to USB drives. The drive must be bigger than the iso and the drive size will be truncated to the size of the iso. To recover lost storage, use Window's Disk Management tool. Release 1.1.1004 WIN32 release 25 January 2011 - Fixed an issue that would occur if more than one drives are being processed at once (happened sporadically). - Added "-d" command line option that will log additional debug info - Fixed typos Release 1.1.1003 WIN32 release 22 December 2010 - Notification/prompt when imaging finishes. - Option for post image verification for both creating from and writing from usb drives. Previously, writing to drives always was verified. Verification may double the imaging time. - Each image created with imageUSB will have an accompanying log file written with checksum values calculated during the creation process. - MD5 & SHA1 checksum calculation implemented - Now with more warning prompts! To prevent accidently destroying data. - Simultaneous image creation is now supported. See the help documentation for naming convention used. - Running imageUSB with -l command line will save a log (The same one as seen at the bottom of the GUI). Release 1.1.1002 WIN32 release 15 December 2010 - Fixed issue with overall progress bar not updating for subsequent writes after aborting. - Cosmetic / UI changes/fixes - Signed Executable Release 1.1.1001 WIN32 release 8 December 2010 - Concurrent image writing to UFD. - Asthetics Changes. Release 1.1.1000 WIN32 release 1 December 2010 - GUI version. Release 1.0.1001 WIN32 release 23 July 2010 - The USB Flash Drive data is now verified. Release 1.0.1000 WIN32 release 17 June 2010 - First version. Support ======= For technical support, questions, suggestions, please check the help file for our email address or visit our web page at http://www.passmark.com Enjoy.. The PassMark Development team
Master the principles and techniques of multithreaded programming with the Java 8 Concurrency API, About This Book, Implement concurrent applications using the Java 8 Concurrency API and its new componentsImprove the performance of your applications or process more data at the same time, taking advantage of all of your resources.Construct real-world examples related to machine learning, data mining, image processing, and client/server environments, Who This Book Is For, If you are a competent Java developer with a good understanding of concurrency but have no knowledge of how to effectively implement concurrent programs or use streams to make processes more efficient, then this book is for you., What You Will Learn, Design concurrent applications by converting a sequential algorithm into a concurrent oneDiscover how to avoid all the possible problems you can get in concurrent algorithmsUse the Executor framework to manage concurrent tasks without creating threadsExtend and modify Executors to adapt their behavior to your needsSolve problems using the divide and conquer technique and the Fork/Join frameworkProcess massive data sets with parallel streams and Map/Reduce implementationControl data-race conditions using concurrent data structures and synchronization mechanismsTest and monitor concurrent applications, In Detail, Concurrency programming allows several large tasks to be divided into smaller sub-tasks, which are further processed as individual tasks that run in parallel. All the sub-tasks are combined together once the required results are achieved; they are then merged to get the final output. The whole process is very complex. This process goes from the design of concurrent algorithms to the testing phase where concurrent applications need extra attention. Java includes a comprehensive API with a lot of ready-to-use components to implement powerful concurrency applications in an easy way, but with a high flexibility to adapt these components to your needs., The book starts with a full description of design principles of concurrent applications and how to parallelize a sequential algorithm. We'll show you how to use all the components of the Java Concurrency API from basics to the most advanced techniques to implement them in powerful concurrency applications in Java., You will be using real-world examples of complex algorithms related to machine learning, data mining, natural language processing, image processing in client / server environments. Next, you will learn how to use the most important components of the Java 8 Concurrency API: the Executor framework to execute multiple tasks in your applications, the phaser class to implement concurrent tasks divided into phases, and the Fork/Join framework to implement concurrent tasks that can be split into smaller problems (using the divide and conquer technique). Toward the end, we will cover the new inclusions in Java 8 API, the Map and Reduce model, and the Map and Collect model. The book will also teach you about the data structures and synchronization utilities to avoid data-race conditions and other critical problems. Finally, the book ends with a detailed description of the tools and techniques that you can use to test a Java concurrent application., Style and approach, A complete guide implementing real-world examples with algorithms related to machine learning, data mining, and natural language processing in client/server environments. All the examples are explained in a step-by-step approach.
lambdas Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii 1. Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Why Did They Need to Change Java Again? 1 What Is Functional Programming? 2 Example Domain 3 2. Lambda Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Your First Lambda Expression 5 How to Spot a Lambda in a Haystack 6 Using Values 8 Functional Interfaces 9 Type Inference 11 Key Points 13 Exercises 14 3. Streams. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 From External Iteration to Internal Iteration 17 What’s Actually Going On 20 Common Stream Operations 21 collect(toList()) 22 map 22 filter 24 flatMap 25 max and min 26 A Common Pattern Appears 27 reduce 28 Putting Operations Together 30 Refactoring Legacy Code 31 iii Multiple Stream Calls 34 Higher-Order Functions 36 Good Use of Lambda Expressions 36 Key Points 37 Exercises 37 Advanced Exercises 39 4. Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Using Lambda Expressions in Code 41 Primitives 42 Overload Resolution 45 @FunctionalInterface 47 Binary Interface Compatibility 47 Default Methods 48 Default Methods and Subclassing 49 Multiple Inheritance 52 The Three Rules 53 Tradeoffs 54 Static Methods on Interfaces 54 Optional 55 Key Points 56 Exercises 57 Open Exercises 58 5. Advanced Collections and Collectors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Method References 59 Element Ordering 60 Enter the Collector 62 Into Other Collections 62 To Values 63 Partitioning the Data 64 Grouping the Data 65 Strings 66 Composing Collectors 67 Refactoring and Custom Collectors 69 Reduction as a Collector 76 Collection Niceties 77 Key Points 78 Exercises 78 6. Data Parallelism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Parallelism Versus Concurrency 81 iv | Table of Contents Why Is Parallelism Important? 83 Parallel Stream Operations 83 Simulations 85 Caveats 88 Performance 89 Parallel Array Operations 92 Key Points 94 Exercises 94 7. Testing, Debugging, and Refactoring. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Lambda Refactoring Candidates 97 In, Out, In, Out, Shake It All About 98 The Lonely Override 98 Behavioral Write Everything Twice 99 Unit Testing Lambda Expressions 102 Using Lambda Expressions in Test Doubles 105 Lazy Evaluation Versus Debugging 106 Logging and Printing 106 The Solution: peek 107 Midstream Breakpoints 107 Key Points 108 8. Design and Architectural Principles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Lambda-Enabled Design Patterns 110 Command Pattern 110 Strategy Pattern 114 Observer Pattern 117 Template Method Pattern 119 Lambda-Enabled Domain-Specific Languages 123 A DSL in Java 124 How We Got There 125 Evaluation 127 Lambda-Enabled SOLID Principles 127 The Single Responsibility Principle 128 The Open/Closed Principle 130 The Dependency Inversion Principle 134 Further Reading 137 Key Points 137 9. Lambda-Enabled Concurrency. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Why Use Nonblocking I/O? 139 Callbacks 140 Table of Contents | v Message Passing Architectures 144 The Pyramid of Doom 145 Futures 147 Completable Futures 149 Reactive Programming 152 When and Where 155 Key Points 155 Exercises 156 10. Moving Forward 159

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值