artificial-intelligence-codes-coding-247791.jpg
参考答案
这个问题考察的是对Linux命令的熟悉程度,以及对Java中集合操作的综合运用,自从转到Java 8以后,我就一直使用流来处理集合了,下面的代码就是我用流来实现的参考答案
package org.java.learn.java8.stream;
import java.io.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ShellExample {
public static void main(String[] args) throws IOException {
//cat命令,相当于是读取文件中的所有行,并输出
File file = new File("/Users/duqi/IdeaProjects/LearnJava/src/main/java/org/java/learn/java8/stream/t1.txt");
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
List lines = new ArrayList<>();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
lines.add(str);
}
//grep a,相当于filter
lines = lines.stream().filter(s -> s.contains("a")).collect(Collectors.toList());
//sort 按照字典序从小到大排序
lines = lines.stream().sorted().collect(Collectors.toList());
//uniq -c,统计相同的元素的个数
Map integerMap =
lines.stream().sorted().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
//sort -rn,排序后逆序输出
List res =