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;}@Overridepublic int compareTo(Person p) {return this.name.compareTo(p.name);}@Overridepublic 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

java treeset_Java TreeSet相关推荐

  1. Java集合TreeSet

    TreeSet Set接口的一个实现类 内部采用自平衡的排序二叉树,来存储元素 这样,可以保证集合中没有重复元素 并且,可以对元素进行排序 package bhz.aio;import java.ut ...

  2. java set iterator_Java中的TreeSet的iterator()方法 Java.util.TreeSet.iterator() - Break易站

    Java中的TreeSet Java.util.TreeSet.iterator()方法用于返回与TreeSet相同元素的迭代器.元素以随机顺序从树集中的内容返回. 句法: Iterator iter ...

  3. [Java基础]TreeSet集合概述和特点

    练习代码如下: package TreeSetPack;import java.util.TreeSet;public class TreeSetDemo {public static void ma ...

  4. java treeset比较,java中TreeSet的两种排序比较的方式

    第一种是使得元素具有比较性 第二种是让集合具有比较性 具体代码步骤如下: import java.util.*; /* * TreeSet:可以自动对对集合中的元素进行排序 * 第一种比较方式 * 步 ...

  5. java基础—TreeSet集合中储存自定义对象(java集合二)

    TreeSet集合中储存学生对象,按照其年龄进行排序 TreeSet对元素进行排序的方式一: 让元素自身具备比较功能,元素就需要实现Comparable接口,覆盖compareTo方法. TreeSe ...

  6. java subset_Java TreeSet subSet()方法

    Java TreeSet subSet()方法 java.util.TreeSet.subSet(E fromElement,boolean fromInclusive,E toElement,boo ...

  7. Java基础——TreeSet

    TreeSet是SortedSet接口的实现类,Sorted的英文意思是分类的:选择的. TreeSet可以确保集合元素处于排序状态.与HashSet集合相比,TreeSet还提供了如下几个额外方法: ...

  8. java subset_Java中的TreeSet的subSet()方法 Java.util.TreeSet.subSet() - Break易站

    Java中的TreeSet Java.util.TreeSet.subSet()用于返回参数中提到的范围内现有TreeSet的子集.该方法采用上限和下限并返回该范围中提到的所有元素.如果元素存在于集合 ...

  9. (JAVA)TreeSet

    package homework;/*** @author Alina* @date 2021年09月22日 10:34 下午*/ class SetTestStudent implements Co ...

最新文章

  1. pandas读取csv文件,变换文件格式,并转换成numpy数组,取出数据
  2. 为什么一个程序申请的内存有限制_为什么要做自己的小程序商城,做一个要多久?...
  3. 嫦娥之死天蓬元帅的转世
  4. MapReduce太慢了,记一次对它的调优建议。
  5. 爬虫python下载视频_用python做爬虫下载视频
  6. Android如何在测试程序中删除被测应用私有的原始数据
  7. 昆仑通态复制的程序可以用吗_昆仑通态专题(七):MCGS组态软件的设备窗口...
  8. python3 正则表达式模块re相关
  9. oracle leg函数,oracle对象 约束索引 游标 函数
  10. Linux下的free命令
  11. 机器学习(一)绪论、算法总结
  12. 汽车电子测试系统搭建
  13. CentOS7关闭rpcbind连带服务
  14. iphone11看信号强度_iphone11信号强度真的会有提升吗
  15. 《LDAP》LDAP自定义objectclass和属性
  16. 心情不美丽,爬了一些美图,独自欣赏!
  17. 尚硅谷--Linux篇
  18. 视频剪辑后期处理软件生态
  19. R3 Corda:一个为金融服务设计的分布式账本系统
  20. 【Codecs系列】HEVC-SCC编码技术汇总

热门文章

  1. 数据结构之线性表之顺序存储结构(3)
  2. 同一个页面多个ajax提交,速度缓慢
  3. My Data Sructure TemplatesClass
  4. Magento 获取分类的父分类和子分类
  5. 5. 公元二OO七年
  6. python - Flask 基础(1)
  7. 用LinkedList方法模拟栈的数据结构
  8. Android APK反编译详解(转)
  9. DotNetBar 中Ribbon汉化
  10. 信息发布系统 Jquery+MVC架构开发(6)BLL层提供WCF 服务 .