您的位置:首页 > 编程语言 > Java开发

How to write a counter in Java 8?

2015-12-10 10:35 585 查看
Writing a counter in Java can be as simple as 2 lines. In addition to its simplicity, we can also utilize the parallel computation to increase the counter's performance.

import java.util.stream.Collectors;

import java.util.stream.Stream;

import java.util.Map;

 

public class Java8Counter {
public static void main(String[] args) {
String[] arr = { "program", "creek", "program", "creek", "java", "web",
"program" };
Stream<String> stream = Stream.of(arr).parallel();
Map<String, Long> counter = stream.collect(Collectors.groupingBy(
String::toString, Collectors.counting()));
System.out.println(counter.get("creek"));
}

}

When you get the map, you may also want to sort the map by value. Check out this post to see how.

参考: http://www.programcreek.com/2014/01/how-to-write-a-counter-in-java-8/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: