打發(fā)22點(diǎn)~24點(diǎn)
Java中Stream和parallelStream,前者是單管,后者是多管,運(yùn)行時(shí)間上做一個(gè)小對(duì)比伞广,直接上代碼:
/**
*
* @author zhangy6
* <p>對(duì)比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());
}
}
代碼是讀取一個(gè)分詞訓(xùn)練語(yǔ)料疼电,大小7.37MB嚼锄,然后找出其中四個(gè)字的單詞/成語(yǔ),對(duì)比一下Stream和ParallelStream運(yùn)行時(shí)間(筆記本win10)蔽豺,結(jié)果如下:
stream : 317ms
parallelStream : 90ms
多管就是比單管強(qiáng)很多区丑,線程都不用了。