标题翻译
How to avoid duplicate values in a sorted string array?
问题
我发现了这段代码,本来是用来避免重复的数字值,所以我将它改成了考虑字符串元素。它在打印时成功避免了重复的名称,但它并没有按字母顺序对名称进行排序。
我还希望它不要打印出特定的元素"vacant",因为它将在稍后通过输入更新为一个名称。
**这是基于预订系统的,用于按升序排序名称,因此空元素被称为"vacant"。**<br>
请有人能帮帮我。
String[] a = {"Anne", "Anne", "Afrid", "vacant", "vacant", "Sammy", "Dora", "vacant"};
HashSet<String> nameSet = new HashSet<>();
for (int i = 0; i < a.length; i++) {
nameSet.add(a[i]);
}
for (String name : nameSet) {
System.out.println(name + " ");
}
英文翻译
I found this code which was meant to avoid duplicate values for numbers so I changed it to consider String elements.It successfully avoids duplicate names when printing, but it does not sort the names in alphabetic order.
I also hope that it does not print a specific element "vacant", because it will be later updated with a name through an input.
This is based on a booking system to sort names in ascending order,so empty elements are called "vacant".<br>
Please can someone help me.
String[] a ={"Anne","Anne","Afrid","vacant","vacant","Sammy","Dora","vacant"};
HashSet<String> nameSet = new HashSet<>();
for (int i = 0; i < a.length;i++){
nameSet.add(a[i]);
}
for (String name: nameSet) {
System.out.println(name+" ");
}
答案1
得分: 0
这里有一个简单的代码来执行以下操作,
- 去除重复项
- 去除空项
- 去除任何空值
- 对列表进行忽略大小写排序
- 打印它们
public static void main(String argv[]) {
//输入
String[] a = { "Anne", "Anne", "Afrid", "vacant", "vacant", "Sammy", "Dora", "vacant" };
List<String> list = Stream.of(a) //转换为流
.filter(Objects::nonNull) //去除空值
.sorted(new IgnoreCaseStringSorter()) //忽略大小写排序
.distinct() //去除重复项
.filter(name -> !name.equalsIgnoreCase("vacant")) //去除 "vacant"
.collect(Collectors.toList()); //转换为列表
System.out.println("Names: ");
list.stream().forEach(System.out::println);//打印列表
}
static class IgnoreCaseStringSorter implements Comparator<String> {
// 用于按升序排序
public int compare(String a, String b) {
return a.compareToIgnoreCase(b);
}
}
输出:
Names:
Afrid
Anne
Dora
Sammy
英文翻译
Here is a simple code to do the following,
- Removed duplicates
- Removed Vacant
- Removes anything that has null
- Sorts the list ignore case
- Prints them
public static void main(String argv[]) {
//Input
String[] a = { "Anne", "Anne", "Afrid", "vacant", "vacant", "Sammy", "Dora", "vacant" };
List<String> list = Stream.of(a) //Convert to Stream
.filter(Objects::nonNull) //Remove Null values
.sorted(new IgnoreCaseStringSorter()) //Sort ignore case
.distinct() //Remove duplicates
.filter(name -> !name.equalsIgnoreCase("vacant")) //Remove "vacant"
.collect(Collectors.toList()); //Convert to list
System.out.println("Names: ");
list.stream().forEach(System.out::println);//Print the list
}
static class IgnoreCaseStringSorter implements Comparator<String> {
// Used for sorting in ascending order
public int compare(String a, String b) {
return a.compareToIgnoreCase(b);
}
}
Output:
Names:
Afrid
Anne
Dora
Sammy
专注分享java语言的经验与见解,让所有开发者获益!
评论