Java中Stream和parallelStream,前者是单管,后者是多管,运行时间上做一个小对比,直接上代码:
/** * * @author zhangy6 * <p>对比Stream、parallelStream</p> * @date 2017-07-25 */ public class StreamTest { public static void main(String[] args) { String path = "pku_training.utf8"; try { List<String> list = IOUtil.readFile2List(path, "utf-8"); long start = System.currentTimeMillis(); list.stream(). filter(e -> StringUtils.isNotBlank(e)). map(e -> getIdiom(e)). collect(Collectors.toList()); System.out.println("stream : " + (System.currentTimeMillis() - start) + "ms"); start = System.currentTimeMillis(); list.parallelStream(). filter(e -> StringUtils.isNotBlank(e)). map(e -> getIdiom(e)). collect(Collectors.toList()); System.out.println("parallelStream : " + (System.currentTimeMillis() - start) + "ms"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } private static List<String> getIdiom(String string) { String[] array = string.split("\s+"); List<String> list = Arrays.asList(array); return list.stream().filter(e -> e.length() == 4).collect(Collectors.toList()); } }
代码是读取一个分词训练语料,大小7.37MB,然后找出其中四个字的单词/成语,对比一下Stream和ParallelStream运行时间(笔记本win10),结果如下:
stream : 317ms
parallelStream : 90ms
多管就是比单管强很多,线程都不用了。