search
HomeJavajavaTutorialHow to use the TreeSet function in Java for ordered set operations

How to use the TreeSet function in Java for ordered set operations

Jun 26, 2023 pm 02:51 PM
javaordered collectiontreeset

Java's TreeSet is an ordered set implemented based on red-black trees. Its feature is that elements are sorted in order of size, and elements can be quickly added, deleted and searched. This article will introduce how to use the TreeSet function in Java to perform ordered set operations so that it can be better applied in actual programming.

1. Basic operations of TreeSet

1. Create a TreeSet object

To use TreeSet, you need to create a TreeSet object first. You can use the parameterless constructor to create an empty TreeSet, or you can specify a Comparator to customize the collation when creating the TreeSet object.

Sample code:

TreeSet<Integer> set = new TreeSet<>();
TreeSet<String> set2 = new TreeSet<>(new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        // 自定义排序规则
        return o1.compareToIgnoreCase(o2);
    }
});

2. Add elements

Add elements to TreeSet through the add() method. TreeSet will automatically sort elements in order of size, and the same elements will only be saved once.

Sample code:

set.add(3);
set.add(1);
set.add(2);
set.add(3);
// 结果为[1, 2, 3]
System.out.println(set);

3. Delete elements

You can use the remove() method to delete elements in the TreeSet.

Sample code:

set.remove(3);
// 结果为[1, 2]
System.out.println(set);

4. Determine whether an element exists

You can use the contains() method to determine whether an element exists in the TreeSet.

Sample code:

boolean contains = set.contains(2);
// 结果为true
System.out.println(contains);

5. Get the number of elements

You can use the size() method to get the number of elements in the TreeSet.

Sample code:

int size = set.size();
// 结果为2
System.out.println(size);

6. Traverse elements

You can use the for loop or forEach() method to traverse the elements in the TreeSet.

Sample code:

for (Integer i : set) {
    System.out.print(i + " ");
}
System.out.println();

set.forEach(System.out::println);

Output result:

1 2 
1
2

2. Advanced operations of TreeSet

1. Get the first element and the last element

You can use the first() and last() methods to get the first element and the last element in the TreeSet.

Sample code:

Integer first = set.first();
Integer last = set.last();
// 结果为1 2
System.out.println(first + " " + last);

2. Obtain sub-collection

You can use the subSet() method to obtain a sub-collection of TreeSet, which contains fromElement (including) to elements between toElement (exclusive). If fromElement is not specified, it means starting from the first element in the TreeSet.

Sample code:

TreeSet<Integer> subSet = (TreeSet<Integer>) set.subSet(1, 2);
// 结果为[1]
System.out.println(subSet);

TreeSet<String> subSet2 = (TreeSet<String>) set2.subSet("A", "c");
// 结果为[b, C]
System.out.println(subSet2);

It should be noted that if the subcollection changes, the original TreeSet will also change.

3. Get the sub-collection of head or tail elements

You can use the headSet() method and tailSet() method to get the head (excluding toElement) or tail (including fromElement) of the TreeSet A subcollection of elements.

Sample code:

TreeSet<Integer> headSet = (TreeSet<Integer>) set.headSet(2);
// 结果为[1]
System.out.println(headSet);

TreeSet<String> tailSet = (TreeSet<String>) set2.tailSet("b");
// 结果为[b, C]
System.out.println(tailSet);

It should also be noted that if the subcollection changes, the original TreeSet will also change.

4. Get elements that are smaller or larger than the specified element

You can use the lower() method, floor() method, higher() method and ceiling() method to get the element that is smaller or larger than the specified element. Big elements.

Sample code:

Integer lower = set.lower(2);
Integer floor = set.floor(2);
Integer higher = set.higher(1);
Integer ceiling = set.ceiling(1);
// 结果为1 2 2 1
System.out.println(lower + " " + floor + " " + higher + " " + ceiling);

It should be noted that:

  • The difference between the lower() method and the floor() method is: the lower() method obtains the specified ratio The largest element with a smaller element is the largest element that is less than the specified element; and the floor() method obtains the nearest element that is smaller than the specified element, that is, the nearest element that is less than or equal to the specified element.
  • The difference between the higher() method and the ceiling() method is: the higher() method obtains the smallest element that is larger than the specified element, that is, the smallest element that is larger than the specified element; while the ceiling() method obtains the smallest element that is larger than the specified element. The nearest element that is greater than or equal to the specified element.

3. Summary

This article introduces the basic operations and advanced operations of the TreeSet function in Java. Corresponding operation methods can be selected according to actual needs to perform ordered collection operations. It should be noted that when using the subSet() method, headSet() method and tailSet() method, if the subset changes, the original TreeSet will also change, so you need to keep this in mind.

The above is the detailed content of How to use the TreeSet function in Java for ordered set operations. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools