I want to remove the duplicates of userNames in the ArrayList. I've tried to convert the ArrayList to an HashSet, but for some reason it doesn't work. The reason why I chose to convert the ArrayList into a HashSet is because it does not allow duplicated values, however, when I use it on my code, it only changes the order in the list:
My code output:
Choreography - Imran Sullivan
Goodfella - Khalil Person
DarknianIdeal - Sophia Jeffery
DarknianIdeal - Clyde Calderon
Frolicwas - Taylor Vargas
Reliable - Aryan Hess
DarknianIdeal - Liyah Navarro
Deservedness - Eadie Jefferson
Reliable - Angel Whitehouse
Choreography - Priya Oliver
How the output should be:
Choreography - Imran Sullivan
Goodfella - Khalil Person
DarknianIdeal - Sophia Jeffery
Frolicwas - Taylor Vargas
Reliable - Aryan Hess
Deservedness - Eadie Jefferson
This is the code. I've splitted the data into an Array so I can print out the data individually.
import java.util.*;
import java.io.*;
public class Task1 {
public static void main(String[] args) {
List<Person> personFile = new ArrayList<>();
Set<Person> splitUserNameList = new HashSet<>(personFile);
try {
BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] personData = fileRead.split(":");
String personName = personData[0];
String userNameGenerator = personData[1];
String[] userNameSplit = userNameGenerator.split(",");
String newUserNameSplit = userNameSplit[0];
Person personObj = new Person(personName, newUserNameSplit);
splitUserNameList.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
for (Person userNames: splitUserNameList) {
System.out.println(userNames);
}
}
}
/* Person Class */
public class Person {
private String personName;
private String userNameGenerator;
public Person(String personName, String userNameGenerator) {
this.personName = personName;
this.userNameGenerator = userNameGenerator;
}
public String getPersonName() {
return personName;
}
public String getUserNameGenerator() {
return userNameGenerator;
}
@Override
public String toString() {
return userNameGenerator + " - " + personName;
}
}