Bea.AI coding blog
  • Tree
    • Tree Traverse
    • Iteration based traverse
    • Typical problems and solutions
      • Max width of binary tree
      • Binary Tree & BST Serialize & Deserialize
      • Lowest common ancestor (LCA) for Binary Tree and BST
      • Subproblem-based Approach for Resolving Max Value on Trees
      • Path sum III
  • Graph
  • Data structure
    • Java data structure
  • Algorithm general templates
    • Tree
    • Trie
    • Graph
  • Java Algorithm Tips and Tricks
    • Java concurrent list
  • Coding patterns & Strategies
  • Coding patterns & template
    • 1. Binary Search
    • 2. Two Pointer
    • 3. Sliding Window
    • 4. Backtracking
    • 5. DFS
    • 6. BFS
    • 7. Stack
    • 8. Heap
    • 9. Prefix Sum
    • 10. Linked List
    • 11. BST
    • 12. Line sweep
    • 14. Tree
    • 15. Graph
    • 16. Bit manipulation
    • 17. Matrix
    • 18. Monotonic Stack
    • 19. Sorting
    • 20. Union Find
    • 21. Trie
    • 22. Dynamic programming
    • 23. Customized Data Structure
  • Code interview steps
  • Leetcode
    • Tree
      • Traversal
      • Construction and Conversion
      • Search and Validation
      • Manipulation and Modification
      • Special Trees
      • Miscellaneous
    • Dynamic programing
      • Classic DP Problems
      • Sequence/Array DP
      • Matrix DP
      • Knapsack Problems
      • String DP
      • Tree/Graph DP
      • Optimization Problems
      • Combinatorial DP
    • DFS
      • Graph Traversal
      • Path Finding
      • Tree Traversal
      • Backtracking
      • Topological Sorting
      • Traversal Order
      • Dynamic Programming with DFS
      • Connected Components
    • BFS
      • Graph
      • Tree
      • Matrix
      • String
      • Others
    • Two points
      • Array
      • String
      • Linked List
      • Sorting
      • Others
    • LinkedList
      • Basic Operations
      • Cycle Detection and Handling
      • Intersection and Union
      • Partitioning and Merging
      • Palindrome
      • Miscellaneous
    • Backtracking
    • Binary Search
    • Union Find
    • Trie
    • Sort
    • Heap
    • Randomness
    • Topological sort
    • Stack
    • HashTable
    • Sliding Window
  • Blind 75
    • Array
    • Binary
    • Dynamic Programming
    • Graph
    • Interval
    • LinkedList
    • Matrix
    • String
    • Tree
    • Heap
  • Companies
    • Apple
Powered by GitBook
On this page
  • 一、String
  • 1.方法
  • 构造
  • 2.与其他类型转换
  • 二、StringBuffer
  • 1.方法
  • 三、ArrayList(可以重复),Set(不能重复)
  • 1.方法
  • 四、HashMap:底层<Set,List>
  • 1.方法
  • 2.遍历
  • 五、PriorityQueue (堆)
  • 1.方法
  • 2.用法
  • 六、Stack
  • 七、Queue
  • 八、Dequeue 双向队列
  • ArrayDeque
  • 九、LinkedHashSet
  • 十、HashSet
  • Methods of Java HashSet class
  • 十一、TreeSet
  • 十二、LinkedHashMap
  • 十三、TreeMap
  • 十四、自定义排序

Java Algorithm Tips and Tricks

PreviousGraphNextJava concurrent list

Last updated 1 year ago

在LeetCode上刷题自己常用的java类方法,总结了一下:

一、String

1.方法

常用方法:

返回类型
用法
作用

int

length()

返回字符串的长度

char

charAt(int)

返回某索引处的字符

boolean

isEmpty()

判断是否是空字符串

String

toLowerCase()

使用默认语言环境,将 String 中的所字符转换为小写

String

toUpperCase()

使用默认语言环境,将 String 中的所字符转换为大写

String

trim()

返回字符串的副本,忽略前导空白和尾部空白

boolean

equals(Object)

比较字符串的内容是否相同

boolean

equalsIgnoreCase(String)

与equals方法类似,忽略大小写

String

concat(String)

将指定字符串连接到此字符串的结尾。 等价于用“+”

int

compareTo(String)

比较两个字符串的大小

String

substring(int beginIndex)

返回一个新的字符串,它是此字符串的从beginIndex开始截取到最后的一个子字符串。

String

substring(int beginIndex, int endIndex)

返回一个新字符串,它是此字符串从beginIndex开始截取到endIndex(不包含)的一个子字符串。

boolean

endsWith(String suffix)

测试此字符串是否以指定的后缀结束

boolean

startsWith(String prefix)

测试此字符串是否以指定的前缀开始

boolean

startsWith(String prefix, int toffset)

测试此字符串从指定索引开始的子字符串是否以指定前缀开始

boolean

contains(CharSequence s)

当且仅当此字符串包含指定的 char 值序列时,返回 true

int

indexOf(String str)

返回指定子字符串在此字符串中第一次出现处的索引,未找到返回-1

int

indexOf(String str, int fromIndex)

返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始,未找到返回-1

int

lastIndexOf(String str)

返回指定子字符串在此字符串中最右边出现处的索引,未找到返回-1

int

lastIndexOf(String str, int fromIndex)

返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,未找到返回-1

替换

返回类型
用法
作用

String

replace(char oldChar, char newChar)

返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所 oldChar 得到的。

String

replace(CharSequence target, CharSequence replacement)

使用指定的字面值替换序列替换此字符串所匹配字面值目标序列的子字符串。

String

replaceAll(String regex, String replacement)

使用给定的replacement 替换此字符串所匹配给定的正则表达式的子字符串。

String

replaceFirst(String regex, String replacement)

使用给定的replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。

匹配:

返回类型
用法
作用

boolean

matches(String regex)

告知此字符串是否匹配给定的正则表达式。

切片:

返回类型
用法
作用

String[]

split(String regex)

根据给定正则表达式的匹配拆分此字符串。

String[]

split(String regex, int limit)

根据匹配给定的正则表达式来拆分此字符>串,最多不超过limit个,如果超过了,剩下的全部都放到最后一个元素中。

构造

1、构造方法

public String() 
public String(char[] cs)
public String(byte[] bs)
//byte bytes[]={97,98,99};
//String str=new String(bytes) 会新建一个 "abc"

比较

public boolean euqals(Object obj)
public boolean equalsIgnoreCase(String obj)

public int compareTo(String str)//两字符串完全相同返回0; 当前字符串小于参数字符串返回负数;大于返回正数
public int compareToignoreCases(String str)
    
//而用==号 对于引用数据类型判断的是两侧是否指向同一个对象

基本功能

//获取长度
public int length() 
//将参数字符串连接到本字符串的末尾
public String concat(String str)
//获取某一个char
public char charAt(int index) //注意不能像C++那样 数组下标访问  注意是从0开始
//找参数字符串第一次出现的位置
public int indexOf(String str)//可把参数类型String 改成int 查找某个字符 ,而且可以lastIndexOf 找最大的下标,也即从后往前找
public int indexOf(String str,int fromIndex)

//截取得到子串
public String substring(int beginIndex)//从beginIndex到结尾
public String substring(int beginIndex,int endIndex)//注意是[beginIndex,endIndex)
//判空
public boolean isEmpty()

转化(String -> others)

//将此字符串转换为新的字符数组
public char[] toCharArray ()   //String->CharArray->String  这个应该很有用!!!
//使用平台的默认字符集将该 String编码转换为新的字节数组
public byte[] getBytes ()
    
还可以用各个包装类的静态方法
如:Boolean.parseBoolean(String str)  
    Integer.parseInt(String str) 
    经过一些实验对于任何非"true"字符串,parseBoolean总是false,
    对于非数字字符串,parseInteger会报错

转化(others->String)

1、	数组 加 构造方法
2、	一般方法是 直接 str+""就行了
3、	还可以调用String的静态方法 valueof()
 				String str=String.valueOf(100)

替换

//替换
public String replace (CharSequence target, CharSequence replacement) 
//例子:
String str = "itcast itheima";     
String replace = str.replace("it", "IT");     
System.out.println(replace); // ITcast ITheima 

拆分

//将此字符串按照给定的regex(规则)拆分为字符串数组
public String[] split(String regex)
//例子:
String s = "aa|bb|cc";     
String[] strArray = s.split("|"); // ["aa","bb","cc"] 

在Java中,不管是String.split(),还是正则表达式,有一些特殊字符需要转义, 这些字符是 ( [ { / ^ - $ ¦ } ] ) ? | * + . 转义方法为字符前面加上"\",这样在split、replaceAll时就不会报错了; 不过要注意,String.contains()方法不需要转义。

所以正常的写法是这样的: 1、如果用“.”作为分隔的话,必须是如下写法:String.split(“\.”),这样才能正确的分隔开,不能用String.split(“.”); 2、如果用“|”作为分隔的话,必须是如下写法:String.split(“\|”),这样才能正确的分隔开,不能用String.split(“|”); “.”和“|”都是转义字符,必须得加"\“; 3、如果在一个字符串中有多个分隔符,可以用“|”作为连字符,比如:“a=1 and b =2 or c=3”,把三个都分隔出来,可以用String.split(“and|or”); split分隔符总结 1.字符”|“,”*“,”+“都得加上转义字符,前面加上”\“。 2.而如果是” \ “,那么就得写成”\“。 3.如果一个字符串中有多个分隔符,可以用”|"作为连字符。

大小写

public String toLowerCase()
public String toUpperCase()

去掉首尾空白符

public String trim() 

补充:字符串池

  1. 程序当中直接写上的双引号字符串,就在字符串常量池中

  2. 用+ 得到的

new出来的不在

2.StringBuilder与StringBuffer

当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类。

和 String 类不同的是,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象。

StringBuilder 类在 Java 5 中被提出,它和 StringBuffer 之间的最大不同在于 StringBuilder 的方法不是线程安全的(不能同步访问)。

  1. 由于 StringBuilder 相较于 StringBuffer 有速度优势,所以多数情况下建议使用 StringBuilder 类。

  2. 然而在应用程序要求线程安全的情况下,则必须使用 StringBuffer 类。

可变字符序列 StringBuilder是个字符串的缓冲区,即它是一个容器,容器中可以装很多字符串。并且能够对其中的字符串进 行各种操作。

构造方法:

public StringBuilder()
public StringBuilder(String str)   // String -> StringBuilder 

常用方法:

public StringBuilder append(...) 

例如:

StringBuilder builder= new StringBuilder();
StringBuilder bulider2=builder.append("Hello");
builder.append(100).append(false);
builder.append(true); 

用toString方法把StringBuilder转化成String //StringBuilder -> String

2.与其他类型转换

(1)与基本数据类型、包装类之间的转换

1.String –> 基本数据类型、包装类:调用包装类的静态方法 parseXxx(str)

  • int num = Integer.parseInt(str);

2.基本数据类型、包装类 –> String:调用String重载的 valueOf(xxx)

  • String str = str.valueOf(num);

(2)与字符数组之间的转换

1.String –> char[]:调用String的toCharArray()

  • char[] charArray = str.toCharArray();

2.char[] –> String:调用String的构造器

  • char[] arr = new char[]{‘h’,’e’,’l’,’l’,’o’};

  • String str = new String(arr);

(3)与StringBuffer、StringBuilder之间的转换

1.String –> StringBuffer、StringBuilder:调用StringBuffer、StringBuilder构造器

  • StringBuffer sb = new StringBuffer(String str);

2.StringBuffer、StringBuilder –> String: ①调用String构造器;

  • String str = new String(StringBuffer sb);

②StringBuffer、StringBuilder的toString()

  • String str = sb.toString();

二、StringBuffer

StringBuffer sb = new StringBuffer(String str);

1.方法

1.增:append(xxx) 2.删:delete(int start,int end) 3.改:setCharAt(int n, char ch) / replace(int start, int end, String str)

4.查:charAt(int n ) 5.插:insert(int offset, xxx) 6.长度:length(); 7.遍历:for() + charAt() / toString()

三、ArrayList(可以重复),Set(不能重复)

List arrayList = new ArrayList<>(); Set set = new HashSet<>();

1.方法

1.增:add(Object obj) 2.删:remove(int index) / remove(Object obj) 3.改:set(int index, Object ele) 4.查:get(int index) 5.插:add(int index, Object ele) 6.长度:size() 7.清空:clear(); 8.是否包含:contains(Object obj) 9.是否为空:isEmpty() 10.遍历:

  • ① Iterator迭代器方式

  • ② 增强for循环

  • ③ 普通的循环

注意:

  1. ArrayList对象不能存储基本类型,只能存储引用类型的数据。类似 < int > 不能写,但是存储基本数据类型对应的 包装类型是可以的。所以,想要存储基本类型数据, <> 中的数据类型,必须转换后才能编写

  2. 可以直接sout 变量名 回输出这种形式的[AAA,BBB,CCC] toString方法已经重写

  3. 不必重写equals方法和hashcode

四、HashMap:底层<Set,List>

1.方法

1.添加:put(Object key,Object value) 2.删除:remove(Object key) 3.修改:put(Object key,Object value) 4.查询:get(Object key) 5.长度:size() 6.遍历:keySet() / values() / entrySet() 7.containsKey(Object key) 包含返回true,否则false 8.getOrDefault(Object key, int 0) 得到key对应的value,如果不存在返回自己设定的默认值

2.遍历

(1)通过键值对entrySet()

Map<Integer, Integer> map = new HashMap<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

(2)通过keySet()和values()

Map<Integer, Integer> map = new HashMap<>();//迭代key,

for (Integer key : map.keySet()) {
 System.out.println("Key = " + key);
} //迭代value

for (Integer value : map.values()) {
 System.out.println("Value = " + value);
}

(3)使用带泛型的迭代器进行遍历

Map<Integer, Integer> map = new HashMap<>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
 Map.Entry<Integer, Integer> entry = entries.next();
 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

(4)使用不带泛型的迭代器进行遍历

Map map = new HashMap();
Iterator<Map.Entry> entries = map.entrySet().iterator();
while (entries.hasNext()) {
  Map.Entry entry = (Map.Entry) entries.next();
  Integer key = (Integer) entry.getKey();
  Integer value = (Integer) entry.getValue();
  System.out.println("Key = " + key + ", Value = " + value);
}

(5)通过Java8 Lambda表达式遍历

Map<Integer, Integer> map = new HashMap<>();
map.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));

五、PriorityQueue (堆)

1.方法

返回类型
用法
作用

boolean

add(E e)

将指定的元素插入此优先级队列。

void

clear()

从此优先级队列中移除所有元素。

Comparator<? super E>

comparator()

返回用来对此队列中的元素进行排序的比较器;如果此队列根据其元素的自然顺序进行排序,则返回 null。

boolean

contains(Object o)

如果此队列包含指定的元素,则返回 true。

Iterator

iterator()

返回在此队列中的元素上进行迭代的迭代器。

boolean

offer(E e)

将指定的元素插入此优先级队列。

E

peek()

获取但不移除此队列的头;如果此队列为空,则返回 null。

E

poll()

获取并移除此队列的头,如果此队列为空,则返回 null。

boolean

remove(Object o)

从此队列中移除指定元素的单个实例(如果存在)。

int

size()

返回此 collection 中的元素数。

Object[]

toArray()

返回一个包含此队列所有元素的数组。

boolean

isEmpty()

Returns true if this collection contains no elements

T[]

toArray(T[] a)

返回一个包含此队列所有元素的数组;返回数组的运行时类型是指定数组的类型。

从类 java.util.AbstractQueue 继承的方法: addAll, element, remove

从类 java.util.AbstractCollection 继承的方法: containsAll, isEmpty, removeAll, retainAll, toString

从类 java.lang.Object 继承的方法: clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

从接口 java.util.Collection 继承的方法: containsAll, equals, hashCode, isEmpty, removeAll, retainAll

2.用法

PriorityQueue<Integer> minHeap = new PriorityQueue<>(); //小顶堆,默认容量为11

PriorityQueue<Integer> maxHeap = new PriorityQueue<>((i1, i2) -> i2 - i1); //大堆

六、Stack

Stack<type> stk = new Stack<>();
Method
Modifier and Type
Method Description

boolean

The method checks the stack is empty or not.

E

The method pushes (insert) an element onto the top of the stack.

E

The method removes an element from the top of the stack and returns the same element as the value of that function.

E

The method looks at the top element of the stack without removing it.

int

The method searches the specified object and returns the position of the object.

七、Queue

Java Queue 是一个interface,不能直接实例化

public interface Queue<E> extends Collection<E>

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure.

Java LinkedList class can be used as a list, stack or queue

Queue<String> queue = new LinkedList<>();

Methods of Java Queue Interface

Method
Description

boolean add(object)

It is used to insert the specified element into this queue and return true upon success.

boolean offer(object)

It is used to insert the specified element into this queue.

Object remove()

It is used to retrieves and removes the head of this queue.

Object poll()

It is used to retrieves and removes the head of this queue, or returns null if this queue is empty.

Object element()

It is used to retrieves, but does not remove, the head of this queue.

Object peek()

It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

LinkedList<String> linkedList = new LinkedList<>();

Methods of Java LinkedList

Method
Description

boolean add(E e)

It is used to append the specified element to the end of a list.

void add(int index, E element)

It is used to insert the specified element at the specified position index in a list.

boolean addAll(Collection<? extends E> c)

It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.

boolean addAll(Collection<? extends E> c)

It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.

boolean addAll(int index, Collection<? extends E> c)

It is used to append all the elements in the specified collection, starting at the specified position of the list.

void addFirst(E e)

It is used to insert the given element at the beginning of a list.

void addLast(E e)

It is used to append the given element to the end of a list.

void clear()

It is used to remove all the elements from a list.

Object clone()

It is used to return a shallow copy of an ArrayList.

boolean contains(Object o)

It is used to return true if a list contains a specified element.

Iterator<E> descendingIterator()

It is used to return an iterator over the elements in a deque in reverse sequential order.

E element()

It is used to retrieve the first element of a list.

E get(int index)

It is used to return the element at the specified position in a list.

E getFirst()

It is used to return the first element in a list.

E getLast()

It is used to return the last element in a list.

int indexOf(Object o)

It is used to return the index in a list of the first occurrence of the specified element, or -1 if the list does not contain any element.

int lastIndexOf(Object o)

It is used to return the index in a list of the last occurrence of the specified element, or -1 if the list does not contain any element.

ListIterator<E> listIterator(int index)

It is used to return a list-iterator of the elements in proper sequence, starting at the specified position in the list.

boolean offer(E e)

It adds the specified element as the last element of a list.

boolean offerFirst(E e)

It inserts the specified element at the front of a list.

boolean offerLast(E e)

It inserts the specified element at the end of a list.

E peek()

It retrieves the first element of a list

E peekFirst()

It retrieves the first element of a list or returns null if a list is empty.

E peekLast()

It retrieves the last element of a list or returns null if a list is empty.

E poll()

It retrieves and removes the first element of a list.

E pollFirst()

It retrieves and removes the first element of a list, or returns null if a list is empty.

E pollLast()

It retrieves and removes the last element of a list, or returns null if a list is empty.

E pop()

It pops an element from the stack represented by a list.

void push(E e)

It pushes an element onto the stack represented by a list.

E remove()

It is used to retrieve and removes the first element of a list.

E remove(int index)

It is used to remove the element at the specified position in a list.

boolean remove(Object o)

It is used to remove the first occurrence of the specified element in a list.

E removeFirst()

It removes and returns the first element from a list.

boolean removeFirstOccurrence(Object o)

It is used to remove the first occurrence of the specified element in a list (when traversing the list from head to tail).

E removeLast()

It removes and returns the last element from a list.

boolean removeLastOccurrence(Object o)

It removes the last occurrence of the specified element in a list (when traversing the list from head to tail).

E set(int index, E element)

It replaces the element at the specified position in a list with the specified element.

Object[] toArray()

It is used to return an array containing all the elements in a list in proper sequence (from first to the last element).

<T> T[] toArray(T[] a)

It returns an array containing all the elements in the proper sequence (from first to the last element); the runtime type of the returned array is that of the specified array.

int size()

It is used to return the number of elements in a list.

八、Dequeue 双向队列

public interface Deque<E> extends Queue<E>

Java Deque Interface is a linear collection that supports element insertion and removal at both ends. Deque is an acronym for “double ended queue”.

Methods of Java Deque Interface

Method
Description

boolean add(object)

It is used to insert the specified element into this deque and return true upon success.

boolean offer(object)

It is used to insert the specified element into this deque.

Object remove()

It is used to retrieves and removes the head of this deque.

Object poll()

It is used to retrieves and removes the head of this deque, or returns null if this deque is empty.

Object element()

It is used to retrieves, but does not remove, the head of this deque.

Object peek()

It is used to retrieves, but does not remove, the head of this deque, or returns null if this deque is empty.

ArrayDeque

The ArrayDeque class provides the facility of using deque and resizable-array. It inherits AbstractCollection class and implements the Deque interface.

The important points about ArrayDeque class are:

  • Unlike Queue, we can add or remove elements from both sides.

  • Null elements are not allowed in the ArrayDeque.

  • ArrayDeque is not thread safe, in the absence of external synchronization.

  • ArrayDeque has no capacity restrictions.

  • ArrayDeque is faster than LinkedList and Stack.

Deque<String> deque = new ArrayDeque<String>();
deque.offer("vimal");  
deque.add("mukul");  
deque.offerFirst("jai");  

//deque.poll();  
//deque.pollFirst();//it is same as poll()  
deque.pollLast();

九、LinkedHashSet

Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface. It inherits the HashSet class and implements the Set interface.

The important points about the Java LinkedHashSet class are:

  • Java LinkedHashSet class contains unique elements only like HashSet.

  • Java LinkedHashSet class provides all optional set operations and permits null elements.

  • Java LinkedHashSet class is non-synchronized.

  • Java LinkedHashSet class maintains insertion order.

LinkedHashSet<String> set=new LinkedHashSet();  

set.add("Four");  
set.add("Five");  
Iterator<String> i=set.iterator();  
while(i.hasNext())  
{  
  System.out.println(i.next());  
}

十、HashSet

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

  • HashSet stores the elements by using a mechanism called hashing.

  • HashSet contains unique elements only.

  • HashSet allows null value.

  • HashSet class is non synchronized.

  • HashSet doesn’t maintain the insertion order. Here, elements are inserted on the basis of their hashcode.

  • HashSet is the best approach for search operations.

  • The initial default capacity of HashSet is 16, and the load factor is 0.75.

Methods of Java HashSet class

Various methods of Java HashSet class are as follows:

SN
Modifier & Type
Method
Description

1)

boolean

It is used to add the specified element to this set if it is not already present.

2)

void

It is used to remove all of the elements from the set.

3)

object

It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.

4)

boolean

It is used to return true if this set contains the specified element.

5)

boolean

It is used to return true if this set contains no elements.

6)

Iterator<E>

It is used to return an iterator over the elements in this set.

7)

boolean

It is used to remove the specified element from this set if it is present.

8)

int

It is used to return the number of elements in the set.

9)

Spliterator<E>

It is used to create a late-binding and fail-fast Spliterator over the elements in the set.

十一、TreeSet

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order.

The important points about the Java TreeSet class are:

  • Java TreeSet class contains unique elements only like HashSet.

  • Java TreeSet class access and retrieval times are quiet fast.

  • Java TreeSet class doesn’t allow null element.

  • Java TreeSet class is non synchronized.

  • Java TreeSet class maintains ascending order.

  • Java TreeSet class contains unique elements only like HashSet.

  • Java TreeSet class access and retrieval times are quite fast.

  • Java TreeSet class doesn’t allow null elements.

  • Java TreeSet class is non-synchronized.

  • Java TreeSet class maintains ascending order.

  • The TreeSet can only allow those generic types that are comparable. For example The Comparable interface is being implemented by the StringBuffer class.

TreeSet treeSet = new TreeSet();   
Set syncrSet = Collections.synchronziedSet(treeSet);

Methods of Java TreeSet Class

Method
Description

boolean add(E e)

It is used to add the specified element to this set if it is not already present.

boolean addAll(Collection<? extends E> c)

It is used to add all of the elements in the specified collection to this set.

E ceiling(E e)

It returns the equal or closest greatest element of the specified element from the set, or null there is no such element.

Comparator<? super E> comparator()

It returns a comparator that arranges elements in order.

Iterator descendingIterator()

It is used to iterate the elements in descending order.

NavigableSet descendingSet()

It returns the elements in reverse order.

E floor(E e)

It returns the equal or closest least element of the specified element from the set, or null there is no such element.

SortedSet headSet(E toElement)

It returns the group of elements that are less than the specified element.

NavigableSet headSet(E toElement, boolean inclusive)

It returns the group of elements that are less than or equal to(if, inclusive is true) the specified element.

E higher(E e)

It returns the closest greatest element of the specified element from the set, or null there is no such element.

Iterator iterator()

It is used to iterate the elements in ascending order.

E lower(E e)

It returns the closest least element of the specified element from the set, or null there is no such element.

E pollFirst()

It is used to retrieve and remove the lowest(first) element.

E pollLast()

It is used to retrieve and remove the highest(last) element.

Spliterator spliterator()

It is used to create a late-binding and fail-fast spliterator over the elements.

NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)

It returns a set of elements that lie between the given range.

SortedSet subSet(E fromElement, E toElement))

It returns a set of elements that lie between the given range which includes fromElement and excludes toElement.

SortedSet tailSet(E fromElement)

It returns a set of elements that are greater than or equal to the specified element.

NavigableSet tailSet(E fromElement, boolean inclusive)

It returns a set of elements that are greater than or equal to (if, inclusive is true) the specified element.

boolean contains(Object o)

It returns true if this set contains the specified element.

boolean isEmpty()

It returns true if this set contains no elements.

boolean remove(Object o)

It is used to remove the specified element from this set if it is present.

void clear()

It is used to remove all of the elements from this set.

Object clone()

It returns a shallow copy of this TreeSet instance.

E first()

It returns the first (lowest) element currently in this sorted set.

E last()

It returns the last (highest) element currently in this sorted set.

int size()

It returns the number of elements in this set.

//Creating and adding elements  
  TreeSet<String> al=new TreeSet<String>();  
  al.add("Ravi");  
  al.add("Vijay");  
  al.add("Ravi");  
  al.add("Ajay");  
  //Traversing elements  
  Iterator<String> itr=al.iterator();

十二、LinkedHashMap

Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with predictable iteration order. It inherits HashMap class and implements the Map interface.

Points to remember

  • Java LinkedHashMap contains values based on the key.

  • Java LinkedHashMap contains unique elements.

  • Java LinkedHashMap may have one null key and multiple null values.

  • Java LinkedHashMap is non synchronized.

  • Java LinkedHashMap maintains insertion order.

  • The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Methods of Java LinkedHashMap class

Method
Description

V get(Object key)

It returns the value to which the specified key is mapped.

void clear()

It removes all the key-value pairs from a map.

boolean containsValue(Object value)

It returns true if the map maps one or more keys to the specified value.

Set<Map.Entry<K,V>> entrySet()

It returns a Set view of the mappings contained in the map.

void forEach(BiConsumer<? super K,? super V> action)

It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.

V getOrDefault(Object key, V defaultValue)

It returns the value to which the specified key is mapped or defaultValue if this map contains no mapping for the key.

Set<K> keySet()

It returns a Set view of the keys contained in the map

protected boolean removeEldestEntry(Map.Entry<K,V> eldest)

It returns true on removing its eldest entry.

void replaceAll(BiFunction<? super K,? super V,? extends V> function)

It replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

Collection<V> values()

It returns a Collection view of the values contained in this map.

十三、TreeMap

Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing key-value pairs in sorted order.

The important points about Java TreeMap class are:

  • Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.

  • Java TreeMap contains only unique elements.

  • Java TreeMap cannot have a null key but can have multiple null values.

  • Java TreeMap is non synchronized.

  • Java TreeMap maintains ascending order.

TreeMap<Integer,String> map=new TreeMap<Integer,String>();    
      map.put(100,"Amit");    
      map.put(102,"Ravi");    
      
TreeMap<Integer,String> map=new TreeMap<>((e1, e2) -> e2 - e1);    
        map.put(10, "aa");
        map.put(12, "ddd");
        map.put(8, "cdd");
        
        for(Map.Entry<Integer, String> e : map.entrySet()) {
            System.out.println(e.getKey() + " " + e.getValue());
        }

十四、自定义排序

//自定义二维数组的排序(从小到大)
Arrays.sort(int[][], (o1, o2) -> o1[0] - o2[0]);

Integer[] arr = new Integer[]{1, 4, 3};
Arrays.sort(arr) //升序
Arrays.sort(arr, (o1, o2) -> o2 - o1)); //降序
//For int[], can't use desc sort 

List 排序
Collections.sort(intList); //升序
Collections.sort(intList, (o1, o2) -> o2 - o1); //降序

Character

isLetter(char ch)
isDigit(char ch)
isLetterOrDigit(char ch)
isWhitespace(char ch)
toUpperCase(char ch)
toLowerCase(char ch)
toString(char ch)
compare(char x, char y)
isUpperCase(char ch)
isLowerCase(char ch)

关于split 的转义字符 以下参考

fd87872a01e759860b137110f2f0edfd.png

https://www.imxiaoyu.top/2021/05/30/JAVA刷题常用方法/
https://www.javatpoint.com/java-linkedhashmap
CSDN
菜鸟教程参考
empty()
push(E item)
pop()
peek()
search(Object o)
add(E e)
clear()
clone()
contains(Object o)
isEmpty()
iterator()
remove(Object o)
size()
spliterator()