脚本宝典收集整理的这篇文章主要介绍了java8-模拟hadoop,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
hadoop的入门程序,java8也能实现
@test public void fileWordCount() throws IOException { //特殊文件需要格式转换为txt Files.readAllLines(Paths.get("D:\jd.txt"), StandardCharsets.UTF_8).parallelStream() //将多个流融合为一个 .flatMap(line -> Arrays.stream(line.trim().split("\s"))) .filter(word -> word.length() > 0) .map(word -> new AbstractMap.SimpleEntry<>(word, 1)) .collect(groupingBy(AbstractMap.SimpleEntry :: getKey, counting())) .entrySet().forEach(System.out :: println); }
List统计单词数量程序
@Test public void listWordCount(){ List<String> stringList = Arrays.asList("a","b","c","a"); stringList.stream() .map(s -> new AbstractMap.SimpleEntry<>(s, 1)) .collect(groupingBy(AbstractMap.SimpleEntry :: getKey, counting())) .entrySet().stream() .forEach(System.out :: println); System.out.println("---------------------------------------------------"); //通过自定义reduce统计,其实counting()也使用的是reduce //记住:凡是在中间操作使用了map,接口定义都需要声明出来,直接使用lambda表达式会有1.无法读取method,2.类型检查不到 的问题 BinaryOperator<Integer> binaryOperator2 = Integer::sum; //排序的转换规则接口 ToIntFunction<map.Entry> sortMapFunction = (Map.Entry se) -> Integer.valueOf(se.getValue().toString()).intValue(); stringList .stream() .map(s -> new AbstractMap.SimpleEntry<>(s, 1)) .collect(groupingBy(AbstractMap.SimpleEntry::getKey, reducing(0, AbstractMap.SimpleEntry::getValue,binaryOperator2))) .entrySet() .stream() .sorted(Comparator.comparingInt(sortMapFunction)) .forEach(System.out::println); }
以上是脚本宝典为你收集整理的java8-模拟hadoop全部内容,希望文章能够帮你解决java8-模拟hadoop所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。