我有一个像这样的用户输入名称列表
String [] names = new String[x];
然后让我们说他们输入了这些名字
names = {John, Bill, Sam, John, Joe, Bill};
如何检查此数组中的重复项? 然后我如何打印出重复的名称?
到目前为止,我有这个,但它无法正常工作
boolean duplicatenames = false;
for (int i = 0; i < names.length; i++) {
for (int j = 0; j < names.length -1; j++) {
if (names[i].equals(names[j])) {
duplicatenames = true;
}
}
}
我认为它只是检查是否有重复。但是我如何打印出哪些名称是重复的?
例如:
&#34;名称重复。这些名字是:John,Bill&#34;
答案 0 :(得分:2)
您可以迭代数组,将值保存到频率映射,然后仅过滤掉多次出现的键。 Java 8的流API允许使用相当优雅的语法:
List<String> duplicates =
Arrays.stream(names)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
答案 1 :(得分:0)
提示:
答案 2 :(得分:0)
使用Set
保存重复的名称。按照您的意愿打印它们。
Set<String> duplicateNameSet = new HashSet<String>();
for (int i = 0; i < names.length; i++)
for (int j = 0; j < names.length -1; j++) {
if (names[i].equals(names[j])) {
duplicateNameSet.add(names[j])
}
if(duplicateNameSet.isEmpty())
System.out.println( "There are duplicate names.");
else
System.out.println( "There are duplicate names. These names are: "+duplicateNameSet);
答案 3 :(得分:0)
建立Map
名称以进行反击。要拥有可更新的计数器,请使用AtomicInteger
。然后使用计数器&gt; = 2打印所有地图条目。如果您使用LinkedHashMap
,则值将按照首次看到的原始顺序列出。
String[] names = {"John", "Bill", "Sam", "John", "Joe", "Bill", "John"};
Map<String, AtomicInteger> nameCount = new LinkedHashMap<>(names.length * 4 / 3 + 1);
for (String name : names) {
AtomicInteger count = nameCount.get(name);
if (count == null)
nameCount.put(name, new AtomicInteger(1));
else
count.incrementAndGet();
}
StringBuilder buf = new StringBuilder();
for (Entry<String, AtomicInteger> entry : nameCount.entrySet()) {
String name = entry.getKey();
int count = entry.getValue().get();
if (count > 1) {
if (buf.length() == 0)
buf.append("There are duplicate names. These names are: ");
else
buf.append(", ");
buf.append(name);
if (count > 2)
buf.append(" (").append(count).append(" times)");
}
}
if (buf.length() != 0)
System.out.println(buf);
else
System.out.println("There are no duplicate names.");
<强>输出强>
There are duplicate names. These names are: John (3 times), Bill
答案 4 :(得分:0)
String[] names = {"John","Doe","John","Doe","Hello"};
Set<String> duplicatesNames = new HashSet<String>();
Set<String> testSet = new HashSet<String>();
for(String name : names){
boolean check = testSet.add(name);
if(!check){
duplicatesNames.add(name);
}
}
System.out.println("Duplicates names are " + duplicatesNames);