Question

I am trying to get rid of multiple specific strings. For instance, I have a string that prints:

1.jedi 2.sith 3.sith 4.sith 5.bounty hunter 6.jedi 7.sith 8.robot

My goal is to remove duplicates so that it prints:

  1. jedi
  2. sith
  3. bounty hunter
  4. robot

If I change one of the jedi to "something jedi.", it will not print "something jedi."

Output should be:

1.jedi 2.sith 3.bounty hunter 4.robot 5.something jedi

Right now I am using this code to achieve the task of removing duplicates.

if (department.contains(departmentList.get(empName))){
}
else{
     department += j + ": " + departmentList.get(empName) + "\n";
     j++;
}

I understand where the mistake is. Since I am using .contains(VARIABLE), when it checks "something jedi" it will find that the word JEDI is already there. therefore it returns true and it won't add it to the department.

Was it helpful?

Solution

Create a set to contain the full names of the departments already output. Each time you want to output a department, check if the set contains it already. If not, then output the department name and add it to the set.

For example:

Set<String> usedDepartments = new HashSet<String>();

Then in your loop:

if(!usedDepartments.contains(departmentList.get(empName))) {
    department += j + ": " + departmentList.get(empName) + "\n";
    j++;
    usedDepartments.add(departmentList.get(empName));
}

OTHER TIPS

As your department's value:

department += j + ": " + departmentList.get(empName) + "\n";

You may change your IF statement:

if (department.contains(": " + departmentList.get(empName) + "\n"))

SUPPOSE:

department = "1: something jedi.\n";
departmentList.get(empName) = "jedi.";
department.contains(": " + departmentList.get(empName) + "\n"); // will return false

Firstly, split your String into Link. Secondly, make a Set from it, so it will delete all the repetitions.

department should be a Set<String>, not a String:

Set<String> departments = new HashSet<String>();

then every loop:

departments.add(departmentList.get(empName));

and after the loop:

int i = 0;
String output = "";
for (String s : departments)
    output += i + ": " + s + "\n";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top