[英]Remove and Replace Duplicates in ArrayList
How do I remove duplicate numbers on ArrayList and replace them with new ones? 如何删除ArrayList上的重复数字并将其替换为新的数字?
I want to print the numbers without them duplicating. 我想打印数字而不重复。
This is my code: 这是我的代码:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
int opt = Integer.parseInt(JOptionPane.showInputDialog("How many numbers?");
for (int i=0 ; i < opc ; i++) {
al.add(Integer.parseInt(JOptionPane.showInputDialog("Which numbers?")));
}
Set<Integer> s = new HashSet<>();
for (Integer d : al){
if (s.add(d) == false)
JOptionPane.showMessageDialog(null,"The number " + d + " was duplicated in position " + al.lastIndexOf(d));
JOptionPane.showMessageDialog(null,"Replace new number"); //This is where I would like to replace the numbers if possible
}
JOptionPane.showMessageDialog("Your numbers without duplicates: "); //This is where it would print
}
}
}
Prevent from entering duplicate numbers when the user enters them, instead of checking and replacing them later. 防止在用户输入重复号码时输入重复的号码,而不是以后检查并替换它们。
Do it in this place: 在这个地方做:
for (int i=0 ; i < opc ; i++) {
al.add(Integer.parseInt(JOptionPane.showInputDialog("Which numbers?")));
}
Chceck if a number already exists, if yes then ask for another not duplicated, if yes then add it and ask for next number : 检查是否已存在一个号码,如果是,则询问另一个不重复的号码,如果是,则将其添加并询问下一个号码:
for (int i=0 ; i < opc ; i++) {
int myNumber = Integer.parseInt(JOptionPane.showInputDialog("Which numbers?"));
while( true ){
if( ! al.contains( myNumber ))
al.add( myNumber );
break;
}
myNumber = Integer.parseInt(JOptionPane.showInputDialog("This number is a duplicate, enter another number again"));
}
}
======== EDIT ================== ========编辑==================
I've corrected the example. 我已经纠正了这个例子。 There is missing {
after if
in the above (previous) one: if
上述(上一个)中的{
之后, if
缺少{
public class MmuClass {
public static void main(String... wwwx) {
List<Integer> lst = Arrays.asList(4, 2, 6, -6, 9);
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
int myNumber = Integer.parseInt(JOptionPane.showInputDialog("Which numbers?"));
while (true) {
if (!al.contains(myNumber)) {
al.add(myNumber);
break;
}
myNumber = Integer.parseInt(
JOptionPane.showInputDialog("This number is a duplicate, enter another number again"));
}
al.stream().forEach(System.out::println);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.