[英]Removing brackets from list of anagrams
I have problem with removing brackets 我在移除括号时遇到问题
public class Main {
public static void main(String[] args) throws IOException {
getAnagrams(new InputStreamReader(new URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").openStream(),
StandardCharsets.UTF_8)).forEach(System.out::println);
}
private static String canonicalize(String string) {
return Stream.of(string.split("")).sorted().collect(Collectors.joining());
}
public static List<Set<String>> getAnagrams(Reader rr) {
Map<String, Set<String>> mapa = new BufferedReader(rr).lines().flatMap(Pattern.compile("\\W+")::splitAsStream)
.collect(Collectors.groupingBy(Main::canonicalize, Collectors.toSet()));
return mapa.values().stream().filter(lista -> lista.size() > 1).collect(Collectors.toList());
}
}
The output is 输出是
[hamster, amherst] [仓鼠,阿默斯特]
[genital, gelatin] [生殖器,明胶]
and it should be 它应该是
hamster amherst 仓鼠阿默斯特
genital gelatin 生殖器明胶
You are just printing out your sets, you have getAngarams() that will return List of Sets of Strings, there are many ways to get raw elements without brackets, one of the possibilities is iterator: 您只需要打印出集合,就可以使用getAngarams()返回字符串集合列表,有很多方法可以获取不带括号的原始元素,其中一种可能是迭代器:
Replace your: 更换:
getAnagrams(new InputStreamReader(new URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").openStream(),
StandardCharsets.UTF_8)).forEach(System.out::println);
with: 有:
getAnagrams(new InputStreamReader(new URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").openStream(),
StandardCharsets.UTF_8)).iterator().forEachRemaining(x -> {for (String s : x) System.out.print(s + " ");
System.out.println();});
It is because forEach(System.out::println)
calls the toString()
method inside Set
calss. 这是因为forEach(System.out::println)
调用Set
calss中的toString()
方法。
Add this method to your class 将此方法添加到您的班级
public static void println(Set<String> items) {
for (String item : items) {
System.out.print(item + " ");
}
System.out.println();
}
and replace that code forEach(System.out::println)
with forEach(Main::println)
并将代码forEach(System.out::println)
替换为forEach(Main::println)
or by using this instead of adding new method: 或使用此方法而不是添加新方法:
getAnagrams(new InputStreamReader(new URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").openStream(), StandardCharsets.UTF_8))
.forEach(items -> {
for (String item : items) {
System.out.print(item + " ");
}
System.out.println();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.