程序功能:
输入一串姓名后去重,提供查询功能
源码如下:
import java.util.ArrayList;
//Java how to program, 10th edition
//Exercise 16.13 : (Duplicate Elimination) Write a program that reads in a series of first names and eliminates
//duplicates by storing them in a Set. Allow the user to search for a first name.
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Scanner;
public class DuplicatesElimination
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in); // create scanner
System.out.println("Enter a series of first names:"); // prompt for user input
String input = scanner.nextLine();
// tokenize the input(分割字符串,获取输入值)
String[] tokens = input.split(" ");
// processing input text (将输入值保存为List)
List<String> list = Arrays.asList(tokens);
System.out.printf("List: %s%n", list);
//调用去重方法,显示去重结果,并使用去重后的值构造新的List
List<String> nameList =
new ArrayList<>(getNonDuplicates(list));
//调试经验:如果不排序,调用binarySearch方法时会检索不到结果
Collections.sort(nameList); // sort the ArrayList
System.out.printf("Sorted ArrayList: %s%n", nameList);
// search list for various values(提示用户输入要检索的关键字)
System.out.println("Enter a first name to search:"); // prompt for user input
String searchedName = scanner.nextLine();
printSearchResults(nameList, searchedName); // display search result
scanner.close();
} // end main
//create a Set from a Collection to eliminate duplicates and return the set
//由一个Collection构建一个Set从而实现Collection中元素的去重,并返回Set
private static Collection<String> getNonDuplicates(Collection<String> values)
{
// create a HashSet
Set<String> set = new HashSet<>(values);
System.out.printf("%nNonduplicates are: ");
for (String value : set)
System.out.printf("%s ", value);
System.out.println();
return set;
}
//perform search and display result(完成binarySearch功能并显示结果)
private static void printSearchResults(
List<String> list, String key)
{
int result = 0;
System.out.printf("%nSearching for: %s%n", key);
result = Collections.binarySearch(list, key);
if (result >= 0)
System.out.printf("Found at index %d%n", result);
else
System.out.printf("Not Found (%d)%n",result);
}
} // end class
运行结果:
Enter a a series of first names:
pd pdh hpd huangc168 pandeng huangpandeng pdhuang pd pdh
List: [pd, pdh, hpd, huangc168, pandeng, huangpandeng, pdhuang, pd, pdh]
Nonduplicates are: pd pdh pdhuang huangpandeng pandeng huangc168 hpd
Sorted ArrayList: [hpd, huangc168, huangpandeng, pandeng, pd, pdh, pdhuang]
Enter a first name to search:
pd
Searching for: pd
Found at index 4