Java程序 使用TreeSet删除数组中重复的条目
TreeSet的特征是首要关注的问题,它被广泛用于去除数据结构中的重复部分,如下所示。
- TreeSet实现了SortedSet接口。所以,重复的值是不允许的,会被遗弃。
- TreeSet中的对象是以排序和升序的方式存储的。
- TreeSet不保留元素的插入顺序,但元素是按键排序的。
- 如果我们依靠默认的自然排序,被插入到树中的对象应该是同质的和可比较的。TreeSet不允许插入异质的对象。如果我们试图添加异质的对象,它会在运行时抛出一个classCastException。
步骤: Set的add()方法
在Java中,这里它被用于将一个特定的元素添加到一个Set集合中。只有当指定的元素还没有出现在集合中时,该函数才会添加该元素,否则,如果该元素已经出现在集合中,该函数会返回False。
语法:
boolean add(E element)
Where, E is the type of element maintained
by this Set collection.
步骤:
1.创建一个TreeSet的对象。
2.使用add()方法将数组元素添加到TreeSet中。
3.使用add(element)方法打印和显示数组中被重复的元素。
4.在删除数组中的重复元素后,打印并显示其中的元素。
5.使用size()方法获得TreeSet的大小。
6.使用toArray()方法将上述TreeSet转换为数组,进行转换。
7.对数组元素进行迭代。
8.在删除上述字符串数组中的重复条目后,打印并显示该数组。
实现:
在下面的例子中,我们把数组中的每个元素都加到TreeSet中,然后检查是否有重复的元素。最后,将TreeSet中的所有元素放入Array中,并将Array中所有剩余的空间设为 “null”,然后打印数组中的元素。
示例
// Java Program to remove duplicates entries
// from an Array using TreeSet
// Importing Arrays and TreeSet class from
// java.util package
import java.util.Arrays;
import java.util.TreeSet;
// Class to remove duplicates
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Input custom entries in an array
// String type
// Custom inputs
String[] input
= new String[] { "Hello", "hi", "Wow",
"cute", "thanks", "hi",
"Aww", "cute", "baby",
"beloved", "Aww" };
// Converting Array to String and printing it
System.out.print(
"Initial String Array(Containing Duplicates) : "
+ (Arrays.toString(input)));
// Creating an object of TreeSet
TreeSet<String> dupliCheckr = new TreeSet<String>();
// Adding array elements in TreeSet
// For added elements in TreeSet
for (String element : input) {
// Displaying duplicate entries
if (!dupliCheckr.add(element)) {
// Print and display elements in an array
// which are duplicated.
System.out.println(
"Duplicate Data entered : " + element);
}
}
// Next line
System.out.println();
// Print and display elements in an array
// after removing duplicates from it.
System.out.println(
"TreeSet(After Removing Duplicates) : "
+ dupliCheckr);
// Next line
System.out.println();
// Getting size of TreeSet using size() method
int length = dupliCheckr.size();
// Converting above TreeSet to arrays
// Using toArray() method
input = dupliCheckr.toArray(input);
// Iterating over array elements
for (int i = length; i < input.length; i++)
input[i] = null;
// Print and display above string array
// after removing duplicate entries from it
System.out.println("Final String Array is : "
+ Arrays.toString(input));
}
}
输出
Initial String Array(Containing Duplicates) : [Hello, hi, Wow, cute, thanks, hi, Aww, cute, baby, beloved, Aww]Duplicate Data entered : hi
Duplicate Data entered : cute
Duplicate Data entered : Aww
TreeSet(After Removing Duplicates) : [Aww, Hello, Wow, baby, beloved, cute, hi, thanks]
Final String Array is : [Aww, Hello, Wow, baby, beloved, cute, hi, thanks, null, null, null]