[英]Java equivalent of Perl function to print only unique lines?
Trying to find a java equivalent of this line of Perl code: 试图找到这行Perl代码的Java等效项:
perl -ne 'print unless $a{$_}++'
Did some looking around but to no avail! 环顾四周,但无济于事! Cheers, Ger
干杯,格尔
As it's trivia-like question, not a real production problem, then I suppose that Java 8 is allowed. 由于这是类似琐事的问题,而不是实际的生产问题,因此我想允许使用Java 8。
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PrintUnique {
public static void main(String[] args) {
new BufferedReader(new InputStreamReader(System.in)).lines().distinct()
.forEach(System.out::println);
}
}
Java 6 solution would be like this: Java 6解决方案如下所示:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class PrintUnique {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Set<String> lines = new HashSet<String>();
String line;
while((line = br.readLine()) != null) {
if(lines.add(line))
System.out.println(line);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.