java treeset_Java TreeSet

本文深入探讨了Java TreeSet的特性,包括其作为SortedSet实现的优势,如何使用不同构造函数创建TreeSet,以及如何通过Comparator和Comparable接口定制元素排序。此外,文章还提供了多个示例,展示了TreeSet在实际应用中的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java treeset

Java TreeSet is the most popular implementation of java.util.SortedSet. SortedSet is an interface that extends java.util.Set. Java Sorted Set provides total ordering on its elements.

Java TreeSet是java.util.SortedSet最受欢迎的实现。 SortedSet是扩展java.util.Set接口 。 Java Sorted Set为其元素提供总排序。

Java TreeSet (Java TreeSet)

In other words, while iterating the TreeSet, we can expect sorted data. Java TreeSet elements are ordered as per their natural ordering or we can provide a Comparator while creating SortedSet. If we don’t provide specific Comparator during set creation, elements must implement the Comparable to ensure natural ordering.

换句话说,在迭代TreeSet时,我们可以期望排序后的数据。 Java TreeSet元素按照其自然顺序进行排序,或者我们可以在创建SortedSet提供Comparator 。 如果在集合创建过程中未提供特定的Comparator,则元素必须实现Comparable以确保自然排序。

Java TreeSet构造函数 (Java TreeSet Constructors)

TreeSet is very popular implementation of SortedSet. As per specification, all sorted set implementation classes should provide 4 types of constructors.

TreeSetSortedSet非常流行的实现。 根据规范,所有排序集实现类都应提供4种类型的构造函数。

  1. A void (no arguments) constructor: It should create a sorted set which is sorted according to the natural ordering of its elements.

    一个void(无参数)构造函数:它应该创建一个有序集合,该集合根据其元素的自然顺序进行排序。
  2. A constructor with an argument of type Comparator: It should create a sorted set which is sorted according to the provided Comparator.

    一个参数类型为Comparator的构造函数:应创建一个已排序的集合,该集合根据提供的Comparator进行排序。
  3. A constructor with an argument of type Collection: It should create a sorted set with elements of provided collection which is sorted according to the natural ordering of elements.

    一个参数类型为Collection的构造函数:它应使用提供的collection的元素创建一个排序的集合,该集合根据元素的自然顺序进行排序。
  4. A constructor with an argument of type SortedSet: It should behave as a copy constructor and create a new sorted set with the same elements and the same ordering of provided sorted set.

    参数类型为SortedSet的构造函数:它应充当复制构造函数,并使用提供的排序集合的相同元素和相同顺序创建一个新的排序集合。

Unfortunately, interfaces can’t contain constructors. So, there isn’t any way to enforce these recommendations.

不幸的是,接口不能包含构造函数。 因此,没有任何方法可以执行这些建议。

Java TreeSet示例 (Java TreeSet Example)

Now let’s create a sorted set using different ways, as mentioned earlier we will look at different examples of java TreeSet.

现在,让我们使用不同的方式创建一个排序集,如前所述,我们将研究Java TreeSet的不同示例。

// Create a sorted set of Integers
SortedSet<Integer> setWithNaturalOrdering = new TreeSet<>();
setWithNaturalOrdering.add(5);
setWithNaturalOrdering.add(9);
setWithNaturalOrdering.add(4);
setWithNaturalOrdering.add(2);
setWithNaturalOrdering.forEach(System.out::println);

Output of the above java TreeSet example code will be like below image.

上面的Java TreeSet示例代码的输出将如下图所示。

Java TreeSet可比 (Java TreeSet Comparable)

Now, we’ll create a sorted set with objects of Person class. To, provide natural ordering Person class should have implementation of Comparable interface.

现在,我们将创建一个包含Person类对象的排序集。 要提供自然排序, Person类应具有Comparable接口的实现。

class Person implements Comparable<Person> {
    int id;
    String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public int compareTo(Person p) {
        return this.name.compareTo(p.name);
    }

    @Override
    public String toString() {
        return this.name;
    }
}
// Create a sorted set with user defined class
SortedSet<Person> sortedSet = new TreeSet<>();
sortedSet.add(new Person(1, "Mark"));
sortedSet.add(new Person(2, "Vispi"));
sortedSet.add(new Person(3, "Harmony"));
sortedSet.forEach(System.out::println);

Output:

输出:

Harmony
Mark
Vispi

Java TreeSet比较器 (Java TreeSet Comparator)

To provide different ordering, we need to pass custom comparator implementation while creating sorted set. For instance, let’s sort set according to the id attribute of Person class.

为了提供不同的排序,我们需要在创建排序集时通过自定义比较器实现。 例如,让我们根据Person类的id属性对集合进行排序。

// we can also provide instance of Comparator implementation instead of lambda
SortedSet<Person> customOrderedSet = new TreeSet<>((p1, p2) -> p1.id - p2.id);
customOrderedSet.addAll(sortedSet);
customOrderedSet.forEach(System.out::println);

Java排序集示例 (Java Sorted Set Example)

We can also create sorted set by passing another collection object or a different sorted set.

我们还可以通过传递另一个集合对象或其他排序集来创建排序集。

List<Person> listOfPerson = Arrays.asList(new Person(1, "Mark"), new Person(2, "Vispi"), new Person(3, "Harmony"));
SortedSet<Person> sortedSetFromCollection = new TreeSet<>(listOfPerson);
SortedSet<Person> copiedSet = new TreeSet<>(sortedSetFromCollection);
copiedSet.forEach(System.out::println);

In both the cases we get following output:

在这两种情况下,我们都得到以下输出:

Harmony
Mark
Vispi

Java SortedSet方法 (Java SortedSet Methods)

SortedSet certainly gets some extra privileges as compared to Set because of its sorted nature. As you might have already guessed, apart from inherited methods from the Set interface, it also provides a few additional methods.

与Set相比,SortedSet当然具有一些额外的特权,因为它具有排序的性质。 您可能已经猜到,除了从Set接口继承的方法外,它还提供了一些其他方法。

  1. Comparator<? super E> comparator(): Returns the comparator instance used to order elements in the set. If elements are sorted as per their natural ordering, it returns null.

    Comparator<? super E> comparator() Comparator<? super E> comparator() :返回用于对集合中的元素进行排序的比较器实例。 如果元素按照其自然顺序排序,则返回null。
  2. SortedSet<E> subSet(E fromElement, E toElement): Returns a portion of this set for given range. (fromElement is inclusive whereas toElement is exclusive). Note that it returns a view of the subset. Thus, changes performed on the returned set are reflected in actual set.

    SortedSet<E> subSet(E fromElement, E toElement) :返回给定范围的此集合的一部分。 (fromElement包含在内,而toElement包含在内)。 请注意,它返回该子集的视图。 因此,对返回的集合执行的更改会反映在实际集合中。
  3. SortedSet<E> headSet(E toElement): Returns a view of the portion of this set whose elements are strictly less than toElement.

    SortedSet<E> headSet(E toElement) :返回此集合中元素严格小于toElement的部分的视图。
  4. SortedSet<E> tailSet(E fromElement): Returns a view of the portion of this set whose elements are greater than or equal to fromElement.

    SortedSet<E> tailSet(E fromElement) :返回此集合中元素大于或等于fromElement的部分的视图。
  5. E first(): Returns the first element of the set which happens to be lowest element in the set.

    E first() :返回集合中的第一个元素,恰好是集合中的最低元素。
  6. E last(): Returns the last element of the set which happens to be highest element in the set.

    E last() :返回集合中的最后一个元素,该元素恰好是集合中的最高元素。

Java SortedSet实现 (Java SortedSet Implementation)

Let’s explore these methods with an example. We’ll create a sorted set by passing a comparator. Here, comparator() method will return the same comparator:

让我们通过一个例子来探索这些方法。 我们将通过一个比较器来创建一个排序集。 在这里, comparator()方法将返回相同的比较器:

SortedSet<Integer> intSet = new TreeSet<>(Comparator.naturalOrder());
intSet.addAll(Arrays.asList(7,2,1,4,6,5));
Comparator comparator = intSet.comparator();

Now, let’s find subset using subSet(from, to) method. Note that the changes made on subset are reflected on the original set as well.

现在,让我们使用subSet(from, to)方法查找子集。 请注意,对子集所做的更改也将反映在原始集合上。

SortedSet<Integer> subSet = intSet.subSet(2, 5);
System.out.println(subSet);
subSet.add(3);
System.out.println(intSet);

Output:

输出:

[2, 4]
[1, 2, 3, 4, 5, 6, 7]

Simillarly, let’s check out other methods:

同样,让我们​​看看其他方法:

subSet = intSet.headSet(3);
System.out.println("Head set");
System.out.println(subSet);

subSet = intSet.tailSet(3);
System.out.println("Tail set");
System.out.println(subSet);

System.out.println("Retrieving lowest and highest elements respectively");
System.out.println(intSet.first());
System.out.println(intSet.last());

Output:

输出:

Head set
[1, 2]
Tail set
[3, 4, 5, 6, 7]
Retrieving lowest and highest elements respectively
1
7

That’s all for Java TreeSet or java sorted set.

这就是Java TreeSet或Java排序集的全部内容。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/16182/java-treeset

java treeset

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值