java - Finding Groups of Rearranged Strings from a txt With Strings on Seperate Lines
问题描述
What I would like to do is take an input txt file of any length which looks like this
bob
joe
obb
oej
and produce an output txt file which sorts groups of re-arranged words on a single line and alphabetically in an output txt file.
bob obb
joe oej
Here is what I have attempted so far where args[0]
is a file called input.txt passed in the command line.
public static void main(String[] args) {
File file = new File(args[0]):
Scanner scan = new Scanner(file);
List<char[]> anagrams = new ArrayList();
while (scan.hasNextLine()) {
Scanner scan2 = new Scanner(file);
String line = scan.nextLine();
char[] arr = line.toCharArray();
if (containsAnagram(anagrams, line))
continue;
else anagrams.add(line);
while (scan2.hasNextLine()) {
String line2 = scan2.nextLine();
if (isAnagram(arr, line2))
fileContent2+=” ”+line2;
}
fileContent+=fileContent2+”\n”;
}
}
private static boolean isAnagram(char[] arr, String line) {
for (int i=0; i<arr.length; i++) {
if (!Arrays.asList(line).contains(arr(i))
break;
if (i=arr.length-1)
return true;
}
解决方案
这是使用 java.nio 文件、流和函数实现所需功能的紧凑方法:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class NewClass {
public static void main(String[] args) throws IOException {
// (1)
List<String> input = Files.readAllLines(Paths.get("path to your input file"));
// (2)
Function<String,String> func = s -> Pattern.compile("")
.splitAsStream(s)
.sorted()
.collect(Collectors.joining());
// (3)
List<String> output = input.stream()
.collect(Collectors.groupingBy(func))
.values()
.stream()
.map(list -> list.stream().sorted().collect(Collectors.joining(" ")))
.sorted()
.collect(Collectors.toList());
// (4)
Files.write(Paths.get("path to your output file"), output, Charset.forName("UTF-8"));
}
}
- 将输入文件的所有行读入列表
- 定义一个函数,它接受一个字符串并返回一个带有输入的排序字符的字符串,例如 bob -> bbo
- 按上述函数对输入列表进行分组,将结果映射的值流式传输,将每个列表映射到空格分隔的字符串以形成一行输出文本,将所有字符串收集到输出列表
- 写入输出文件
推荐阅读
- jenkins - Jenkins 构建代理断开连接
- amazon-web-services - Docker 在创建镜像之后和容器启动之前添加文件
- html - Bootstrap 响应式布局设计
- typescript - Highcharts / Typescript:如何使用 scatter3d 旋转?
- rest - FOS OAuth 服务器包在现实生活中的最佳流程是什么?OAuth 2 和 Symfony 4
- javascript - 更新特定对象中的特定属性
- javascript - 从鼠标悬停在另一个元素反应上更新一个元素的样式
- python - 使用 Beautiful Soup/Web Scraping 获取整个单元格信息
- python - 如何使用 Mutagen 和 python 从音乐文件中获取专辑图像?
- javascript - Jx Browser 6.23 比 6.21 慢?