//by ysy 2018年3月6日 public class 统计短单词的数量 { //--------------------统计短单词的个数---------------------------- @Test public void testName0() throws Exception { long count = Files.lines(Paths.get("src/java8.txt"), Charset.defaultCharset()).parallel() // 字符串流--分割--字符串流 .flatMap(str -> Arrays.stream(str.split("[^a-zA-Z]+"))) // 去掉\n .filter(word -> word.length() >0) .filter(word -> word.length() < 12 ) .count(); System.out.println(count); } @Test public void testName_1() throws Exception { // Stream String conts = new String(Files.readAllBytes(Paths.get("src/java8.txt"))); // 将字符串分割为单词 List<String> asList = Arrays.asList(conts.split("[^a-zA-Z]+")); long count = asList.stream() .parallel() .filter(word -> word.length() >0) .filter(s -> s.length() < 12) .count(); System.out.println("短单词个数" + count); } //如何手工统计呢,版本1:不支持并发 @Test public void testName() throws Exception { int count[]=new int[12]; String conts=new String( Files.readAllBytes(Paths.get("src/java8.txt")) ); List<String> asList = Arrays.asList(conts.split("[^a-zA-Z]+")); System.out.println(asList); asList.stream() // .parallel() .forEach(s->{ if (s.length()<12 && s.length()>0) { count[s.length()]++; } }); int sum= IntStream.of(count) .sum(); System.out.println("总个数:"+sum); } //改进,使用AtomicInteger,支持并发 @Test public void testName2() throws Exception { AtomicInteger count = new AtomicInteger(0); String conts=new String( Files.readAllBytes(Paths.get("src/java8.txt")) ); List<String> asList = Arrays.asList(conts.split("[^a-zA-Z]+")); System.out.println(asList); asList.stream() .parallel() .forEach(s->{ if (s.length()<12 && s.length()>0) { count.incrementAndGet(); } }); System.out.println("总个数:"+count.get()); } }
java统计短单词的个数
猜你喜欢
转载自blog.csdn.net/u011165335/article/details/79465316
今日推荐
周排行