user3067251 user3067251 - 1 year ago 39
Java Question

How to allow a user to search for elements

I made a small test class that uses the Set interface to get rid of duplicates in a list. How would I be able to have a user search this list?

Below is the program I have so far:

**Updated I have made a method for the search function, there is an error that breaks the program.

* This program will read a series of first names and eliminate duplicates
* by storing them in a Set. Allow the user to search for a first name.
package Exercises;

* 8/25/2016
* @author Demond
import java.util.List;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Collection;
import java.util.Scanner;

public class Duplicate_Elimination2

private static Scanner scanner = new Scanner(;

public static void main(String[] args)
String[] names = {"Demond", "Demond", "Joe", "Rose", "Ashely"};
List<String> list = Arrays.asList(names);
System.out.printf("List: %s%n", list);


private static void printNonDuplicates(Collection<String> values)
Set<String> set = new HashSet<>(values);

System.out.printf("%nNonduplicates are: ");

for (String value : set)
System.out.printf("%s ", value);


// search names from list
private static void searchNames(String[] names)
// get name from standard input
"Search a name, type end to stop search:");
String inputName =;

// obtain input until end entered
while (!inputName.equals("end"))
// name found
if (names.contains(inputName))
System.out.println(inputName + " found in set");
else // name not found
System.out.println(inputName + " not found in set");

// get next search name
"Search a name, type end to stop search:");
inputName =;

Answer Source

You can't call .contains() on a String[].

The solution is to pass the list to searchNames():


... and then change the parameter type in your searchNames method:

private static void searchNames(List<String> names) {

Of course, your search is performing an exact match, so if you don't get the spelling and capitalisation exactly correct, the name won't be found.