样品输入
"Hello hi hi stackoverflow remain only Hello "
输出:
"stackoverflow remain only"
这是我尝试过的代码
public static void main(String[] args) throws Exception {
String name = "Hello hi stackoverflow remain only Hello hi";
String ar[] = name.split("\\s");
ArrayList<String> dup = new ArrayList<String>();//duplicate words
ArrayList<String> res = new ArrayList<String>();
for (int i = 0; i < ar.length; i++) {
res.add(ar[i]);
String del = ar[i];
for (int j = i + 1; j < ar.length; j++) {
if (ar[j].equals(dup)) {
dup.add(del);
break;
}
}
}
}
for (int i = 0; i < dup.size(); i++) {
for (int j = i + 1; j < res.size(); j++) {
if (st[i].equals(st2[j])) {
res.remove(res.IndexOf(j));
}
}
}
最佳答案
您的代码看起来太复杂了。相反,使用Java-8流库,您可以执行以下操作:
List<String> result =
Pattern.compile("\\s")
.splitAsStream(name)
.collect(Collectors.groupingBy(e -> e,
LinkedHashMap::new,
Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
或者,如果您希望接收者类型为String,则可以使用
joining
收集器。String result =
Pattern.compile("\\s")
.splitAsStream(name)
.collect(Collectors.groupingBy(e -> e,
LinkedHashMap::new,
Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.joining(" "));