Title | Description |
---|---|
Iterable | An interface means that the collection has an iterator and can be circumvented with for (Type value: collection). There are almost all collections (except Map) |
Collection | The main interface for most collections (except Map) |
List | The list is an ordered collection, also known as a sequence. (sequence). Duplicate elements in most implementations are allowed. Allows access by item index Extends the Collection interface. |
Set | Interface that implements work with sets (similar to mathematical sets), duplicating Items are prohibited. It may or may not be orderly. Extends the Collection interface. |
Queue | A queue is a collection designed to store objects before processing, in contrast to the usual operations on collections, a queue provides additional methods for adding, retrieving, and viewing. Fast access on an index of an element, as a rule, does not contain. Extends the Collection interface |
Deque | Two-way queue, supports adding and removing items from both ends. Expands Queue interface. |
Map | Works with matching key - value. Each key corresponds to only one value. AT unlike other collections does not extend any interfaces (including Collection and Iterable) |
SortedSet | Automatically sorted set, or in natural order (for details, see Comparable interface), or using the Comparator. Extends the Set Interface |
SortedMap | This is a map whose keys are automatically sorted, either in natural order, or using comparator Extends the Map interface. |
NavigableSet | This is SortedSet, to which additionally added methods for finding the closest value to the specified search value. NavigableSet can be accessed and accessed or in order. descending values ​​or in ascending order. |
NavigableMap | This is SortedMap, to which additionally added methods for finding the closest value to the specified search value. Available for access and bypass either in descending order of values ​​or in ascending order. |
Title | Description |
---|---|
BlockingQueue | A multi-threaded Queue implementation containing the ability to set the queue size, condition locks, various methods that handle overflows differently when adding or missing data when received (throw an exception, block the stream continuously or temporarily, return false, etc.) |
TransferQueue | This multi-threaded queue can block the insertion stream until the receiving thread pulls the element out of the queue, so that it can be used to implement synchronous and asynchronous message passing between threads. |
Blockingdeque | Similar to BlockingQueue, but for a two-way queue |
Concurrentmap | Interface, extends the Map interface. Adds a number of new atomic methods: putIfAbsent, remove, replace, which make it easier and more secure to make multi-threaded programming. |
ConcurrentNavigableMap | Extends the NavigableMap interface for the multi-threaded version. |
Type of | Single threaded | Multithreaded |
---|---|---|
Lists |
|
|
Queues / Deques |
|
|
Maps |
|
|
Sets |
|
|
Name | Description |
---|---|
Hashtable | Originally conceived as a synchronized analogue of HashMap, when it was not yet possible get the collection version using Collecions.synchronizedMap. At the moment, as a rule use ConcurrentHashMap. HashTable is slower and less thread-safe than synchronous HashMap, since it provides synchronism at the level of individual operations, and not entirely at the level collections. |
Vector | Previously used as a synchronous version of ArrayList, but outdated for the same reasons as HashTable. |
Stack | It used to be used as a queue, but since it is built on the basis of Vector, also considered obsolete. |
Name | Based on | Description |
---|---|---|
Properties | Hashtable | As a data structure built on Hashtable, Properties is a rather outdated construction, it is much better to use a Map containing strings. Read more why Properties not recommended use can be found in this discussion . |
UIDefaults | Hashtable | The collection that stores the default settings for the Swing component. |
Title | Based on | Description | The size* |
---|---|---|---|
ArrayList | List | Implementing a List Interface Based on a Dynamically Variable Array. In most cases, the best possible implementation of the List interface is memory consumption and performance. In extremely rare cases where frequent insertions are required in the beginning or middle of the list with very small by the number of moves through the list, LinkedList will win in performance (but I advise you to use TreeList from apache in these cases). If you are interested in the details of ArrayList I advise you to look at this article . | 4 * N |
Linkedlist | List | Implementing a List of an interface based on a two-way linked list, i.e. when each item indicates the previous and next item. As a rule, it requires more memory and is worse in performance than an ArrayList, it makes sense to use only in rare cases when it is often necessary to insert / delete in the middle of the list with minimal movements in the list (but I advise you to use TreeList from apache in these cases). It also implements Deque interface. When working through the Queue interface, LinkedList acts as a FIFO queue. If you are interested in the details LinkedList I advise you to look at this article . | 24 * N |
Title | Based on | Description |
---|---|---|
CopyOnWriteArrayList | List | The implementation of the List interface, similar to ArrayList, but each time the list is modified, is created new copy of the entire collection. This requires very large resources with every change in the collection, However, this type of collection does not require synchronization, even if the collection is changed during iteration time. |
Title | Based on | Description |
---|---|---|
Rolelist | ArrayList | Collection to store a list of roles (Roles). Highly specialized collection based on ArrayList with several additional methods |
RoleUnresolvedList | ArrayList | Collection to store a list of unresolved roles (Unresolved Roles). Highly specialized ArrayList based collection with several additional methods |
Attributelist | ArrayList | Collection for storing MBean attributes. A highly specialized collection based on ArrayList with several additional methods |
Title | Based on | Description | The size* |
---|---|---|---|
Hashset | Set | Implementing a Set interface using hash tables. In most cases, the best possible implementation of the Set interface. | 32 * S + 4 * C |
LinkedHashSet | Hashset | The implementation of a Set interface based on hash tables and a linked list. Ordered by adding a set that works almost as fast as HashSet. In general, it is almost the same as HashSet, only the order of iteration over the set is determined by the order of adding an element in set for the first time. | 40 * S + 4 * C |
Treeset | NavigableSet | Implement the NavigableSet interface using a red-black tree. Sorted using Comparator or natural order, that is, traversal / iteration over the set will occur depending on the sorting rule. Based on TreeMap, just like HashSet is based on HashMap | 40 * S |
Enumset | Set | A high-performance implementation of a Set vector based on a bit vector. All elements of an EnumSet object must belong to a single enum type. | S / 8 |
Title | Based on | Description |
---|---|---|
JobStateReasons | Hashset | A collection for storing information about print jobs (print job's attribute set). A highly specialized HashSet-based collection with several additional methods. |
Title | Based on | Description |
---|---|---|
CopyOnWriteArraySet | Set | Similarly, CopyOnWriteArrayList with each change creates a copy of the entire set, therefore recommended for very rare collection changes and thread-safe requirements |
ConcurrentSkipListSet | Set | It is a multi-threaded analogue of the TreeSet |
Title | Based on | Description | The size* |
---|---|---|---|
Hashmap | Map | Implementation of the Map interface using hash tables (works as a non-synchronous Hashtable, with support for keys and null values). In most cases, the best in performance and Memory Map implementation interface. If you are interested in the details of the device HashMap I advise you to look at this article . | 32 * S + 4 * C |
LinkedHashMap | Hashmap | The implementation of the Map interface, based on the hash table and the linked list, that is, the keys in the Map stored and managed in the order of addition. This collection works almost as fast as HashMap. It can also be useful for creating caches (see removeEldestEntry (Map.Entry)). If you are interested in the details of the device LinkedHashMap I advise you to look at this article . | 40 * S + 4 * C |
Treemap | NavigableMap | Implementing NavigableMap with a red-and-black tree, that is, while traversing the collection, keys will be sorted in order, also NavigableMap allows you to search for the closest value to the key. | 40 * S |
Weakhashmap | Map | Same as HashMap, but all keys are weak links (weak references), that is, garbage collected can remove objects keys and objects values ​​if there are no other references to these objects. WeakHashMap is one of the easiest ways to take full advantage of weak links. | 32 * S + 4 * C |
Enummap | Map | High-performance implementation of the Map interface based on a simple array. All keys in Only one enum can belong to this collection. | 4 * C |
IdentityHashMap | Map | Identity-based Map, like HashMap, is based on a hash table, but unlike HashMap it never compares objects to equals, only on whether they are really the same and the same object in memory. This is, firstly, greatly accelerates the work of the collection, secondly, it is useful for protection against “spoof attacks” when equals objects are consciously generated by another object. Third, this collection has many uses for traversing graphs (such as deep copying or serialization), when you need to avoid processing a single object several times. | 8 * C |
Title | Based on | Description |
---|---|---|
Concurrenthashmap | Concurrentmap | Multi-threaded analogue of HashMap. All data is divided into separate segments and blocked only. individual segments when changing, which significantly speeds up work in a multi-threaded mode. Iterators never throw a ConcurrentModificationException for this type of collection. |
ConcurrentSkipListMap | ConcurrentNavigableMap | It is a multithreaded analogue of TreeMap |
Title | Based on | Description | The size* |
---|---|---|---|
ArrayDeque | Deque | Effective implementation of the Deque interface, based on a dynamic array, similar ArrayList | 6 * N |
Linkedlist | Deque | The implementation of the List and Deque interface based on a two-way linked list, that is, when each item points to the previous and next item. When working through the Queue interface, LinkedList acts as a FIFO queue. | 40 * N |
PriorityQueue | Queue | Unlimited priority queue based on heap (heap). Items sorted in natural order or using the comparator. Cannot contain null elements. |
Title | Description | The size* |
---|---|---|
Bit set | Despite the name, BitSet does not implement the Set interface. BitSet is used for compact recording of an array of bits. | N / 8 |
Method | Description |
---|---|
frequency (Collection, Object) | Returns the number of occurrences of this item in the specified collection. |
disjoint (Collection, Collection) | Returns true if there are no common items in the two collections. |
addAll (Collection <? super T>, T ...) | Adds all elements from the specified array (or listed in parameters) to the specified collection. |
min (Collection) | Return the minimum item from the collection |
max (Collection) | Returning the maximum item from the collection |
Method | Description |
---|---|
sort (List) | Sorting using the sorting algorithm by the compound (merge sort algorithm), whose performance in most cases is close to the performance of quick sorting (high quality quicksort), is guaranteed by O (n * log n) performance (unlike quicksort), and stability (unlike quicksort). Stable sorting is one that does not change the order of the same elements when sorting. |
binarySearch (List, Object) | Search for an item in the list (list) using the binary search algorithm. |
reverse (List) | Change the order of all elements of the list (list) |
shuffle (list) | Shuffle all items in the list in random order |
fill (List, Object) | Rewriting each item in the list with any value |
copy (List dest, List src) | Copying one list to another |
rotate (List list, int distance) | Moves all items in the list for a specified distance. |
replaceAll (List list, Object oldVal, Object newVal) | Replaces all occurrences of one value with another. |
indexOfSubList (List source, List target) | Returns the index of the first occurrence of the target list in the source list. |
lastIndexOfSubList (List source, List target) | Returns the index of the last occurrence of the target list in the source list. |
swap (List, int, int) | Swaps the items in the specified positions |
Collection | Description of the internal device |
---|---|
ArrayList | This collection is just a setting over the array + variable storing the size of the list. Inside just an array that is recreated every time there is no space to add a new item. AT case, adding or removing an item inside the collection, the entire tail shifts in memory new place. Fortunately, copying an array while increasing capacity or adding / removing elements produced fast native / system methods. If details are interesting I advise you to see this article . |
Linkedlist | Inside the collection is the internal Node class, which contains a link to the previous element, the next element and the value of the element itself. The collection instance itself stores the size and links. on the first and last element of the collection. Considering that the creation of an object is expensive for performance and expensive memory, LinkedList often works slowly and takes much more memory than analogs. Usually ArrayList, ArrayDequery is the best solution for performance and memory, but in some rare cases (frequent insertions in the middle of the list with rare moves through the list), it can be useful (but in this case it is more useful to use TreeList from apache). If you are interested in the details I advise you to see this article . |
Hashmap | This collection is built on a hash table, that is, inside the collection there is an array of the inner class (buket) Node equal to the collection capacity. When a new element is added, its hash function is calculated, divided by capacity HashMap by module, and thus the location of the element in the array is calculated. If there are no elements stored at this place, a new Node object is created with a link to the element being added and is written to the right place in the array. If there is already an element (s) in this place (a hash collision occurs), then so Node is essentially a simply linked list, that is, contains a link to the next element, then you can bypass all the elements in the list and check them on the equals element being added, if this no such match was found, a new Node object is created and added to the end of the list. If the number of elements in a linked list (buket) becomes more than 8 elements, a binary tree is created instead. For more information on hash tables, see the wiki (HashMap uses the chaining method to resolve collisions). If you are interested in the details of the device HashMap I advise you to look at this article . |
Hashset | HashSet is just a HashMap, in which the fake Object is written instead of the value, and only the keys matter. Inside the HashSet is always stored collection HashMap. |
IdentityHashMap | IdentityHashMap is an analogue of HashMap, but it does not require elements to be checked for equals, so how different are any two elements. pointing to different objects. Thanks to this, managed get rid of the internal class Node, storing all the data in one array, while with collisions a suitable free cell is searched until it is found ( method open addressing ). For more on hash tables, see the wiki. (IdentityHashMap uses an open addressing method to resolve collisions) |
LinkedHashMap / LinkedHashSet | The internal structure is almost the same as with HashMap, except that instead of internal class Node, uses a TreeNode, which knows the previous and next value, this allows you to bypass LinkedHashMap in order of adding keys. Essentially LinkedHashMap = HashMap + LinkedList. If you are interested in the details of the device LinkedHashMap I advise you to look at this article . |
TreeMap / TreeSet | The internal structure of these collections is built on a balanced red and black tree, more about it can be read on the wiki |
Weakhashmap | Inside, everything is organized almost as in HashMap, except that instead of the usual links WeakReference is used and there is a separate ReferenceQueue queue that is required to remove Weakentries |
EnumSet / EnumMap | In EnumSet and EnumMap, unlike HashSet and HashMap, bit vectors and arrays are used for compact data storage and accelerated performance. The limitation of these collections is the fact that EnumSet and EnumMap can store only the values ​​of a single Enum as keys. |
Integer sumOddOld = 0; for(Integer i: collection) { if(i % 2 != 0) { sumOddOld += i; } }
Integer sumOdd = collection.stream().filter(o -> o % 2 != 0).reduce((s1, s2) -> s1 + s2).orElse(0);
Integer sumOdd = collection.parallelStream().filter(o -> o % 2 != 0).reduce((s1, s2) -> s1 + s2).orElse(0);
The way to create stream | Creation Template | Example |
---|---|---|
1. Classic: Creating a stream from the collection | collection. stream () | |
2. Creating a stream from values | Stream.of ( value1 , ... valueN ) | |
3. Creating a stream from an array | Arrays.stream ( array ) | |
4. Creating a stream from a file (each line in the file will be a separate element in the stream) | Files.lines ( file_path ) | |
5. Creating a stream from a string | "line". chars () | |
6. Using Stream.builder | Stream. builder (). add (...) .... build () | |
7. Creating a parallel stream | collection. parallelStream () | |
8. Creating endless streams using Stream.iterate | Stream.iterate ( start_condition , expression_generation ) | |
9. Creating Endless Stream with Stream.generate | Stream.generate ( generation_express ) | |
Stream method | Description | Example |
---|---|---|
filter | Filters records, returns only records that match the condition. | collection.stream (). filter ("a1" :: equals) .count () |
skip | Lets skip the first N items. | collection.stream (). skip (collection.size () - 1) .findFirst (). orElse ("1") |
distinct | Returns a stream without duplicates (for the equals method) | collection.stream (). distinct (). collect (Collectors.toList ()) |
map | Converts every element of stream | collection.stream (). map ((s) -> s + "_1"). collect (Collectors.toList ()) |
peek | Returns the same stream, but applies a function to each element of the stream. | collection.stream (). map (String :: toUpperCase) .peek ((e) -> System.out.print ("," + e)). collect (Collectors.toList ()) |
limit | Allows you to limit the sample to a certain number of first elements. | collection.stream (). limit (2) .collect (Collectors.toList ()) |
sorted | Allows you to sort the values ​​either in natural order or by specifying the Comparator | collection.stream (). sorted (). collect (Collectors.toList ()) |
mapToInt , mapToDouble , mapToLong | Analogue map, but returns a numeric stream (that is, a stream of numeric primitives) | collection.stream (). mapToInt ((s) -> Integer.parseInt (s)). toArray () |
flatmap flatMapToInt , flatMapToDouble , flatMapToLong | It looks like a map, but it can create several | collection.stream (). flatMap ((p) -> Arrays.asList (p.split (",")). stream ()). toArray (String [] :: new) |
Stream method | Description | Example |
---|---|---|
findFirst | Returns the first element from the stream (returns Optional) | collection.stream (). findFirst (). orElse ("1") |
findAny | Returns any suitable element from the stream (returns Optional) | collection.stream (). findAny (). orElse ("1") |
collect | Presentation of results in the form of collections and other data structures | collection.stream (). filter ((s) -> s.contains ("1")). collect (Collectors.toList ()) |
count | Returns the number of elements in the stream. | collection.stream (). filter ("a1" :: equals) .count () |
anyMatch | Returns true if the condition is true for at least one element. | collection.stream (). anyMatch ("a1" :: equals) |
noneMatch | Returns true if the condition is not met for one element. | collection.stream (). noneMatch ("a8" :: equals) |
allMatch | Returns true if the condition is true for all items. | collection.stream (). allMatch ((s) -> s.contains ("1")) |
min | Returns the minimum element, uses a comparator as a condition | collection.stream (). min (String :: compareTo) .get () |
max | Returns the maximum element, uses a comparator as a condition | collection.stream (). max (String :: compareTo) .get () |
forEach | Applies a function to each stream object, order when executed in parallel is not guaranteed. | set.stream (). forEach ((p) -> p.append ("_ 1")); |
forEachOrdered | Applies a function to each stream object, preserving the order of the elements guarantees | list.stream (). forEachOrdered ((p) -> p.append ("_ new")); |
toArray | Returns an array of stream values | collection.stream (). map (String :: toUpperCase) .toArray (String [] :: new); |
reduce | Allows you to perform aggregate functions on the entire collection and return a single result. | collection.stream (). reduce ((s1, s2) -> s1 + s2) .orElse (0) |
Stream method | Description | Example |
---|---|---|
sum | Returns the sum of all numbers. | collection.stream (). mapToInt ((s) -> Integer.parseInt (s)). sum () |
average | Returns the arithmetic average of all numbers. | collection.stream (). mapToInt ((s) -> Integer.parseInt (s)). average () |
mapToObj | Converts a numeric stream back to an object. | intStream.mapToObj ((id) -> new Key (id)). toArray () |
Stream method | Description |
---|---|
isParallel | Find out if the stream is parallel |
parallel | Return a parallel stream, if the stream is already parallel, it can return itself |
sequential | Return a consecutive stream, if the stream is already consistent, it can return itself |
Source: https://habr.com/ru/post/314386/
All Articles