import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class HashSetDemo { public static void main(String[] args){ String[] colors={"purple", "green", "red","magenta", "blue", "red", "purple"}; Set<String> set=new HashSet<>(Arrays.asList(colors)); for(String s: set){ System.out.println(s); } } }
for (char c : myString.toCharArray()) {}
The most common PriorityQueue operations are as follows:
boolean offer(E e): Inserts an element at the appropriate location depending on the priority order.
E poll(): Removes the highest priority element, posited it in the front of the queue.
E peek(): Gets a reference to the highest priority element in the queue, but does not remove it.
void clear(): Removes all elements from the queue.
int size(): Gives the number of elements in the queue, or queue size.
The problem with PriorityQueue is that it is not synchronized; therefore, is it not recommended to be used for access with multiple threads. Java, however, provides another class, called PriorityBlockingQueue, which is synchronized.
https://www.javagists.com/2017/04/java-collection-interview-questions-answers.html
http://docs.oracle.com/javase/tutorial/collections/algorithms/index.html
http://java-performance.info/java-collections-overview/
https://habrahabr.ru/company/luxoft/blog/256877/
http://habrahabr.ru/post/267389/ java Collection
https://habrahabr.ru/post/182776/
https://habrahabr.ru/post/156361/
https://www.javacodegeeks.com/2013/02/40-java-collections-interview-questions-and-answers.html
https://www.techempower.com/blog/2017/02/14/enumset-and-enummap/
удалить элементы из середины списка
list.subList(from, to).clear();
найти ключ в Map, соответствующий максимальному значению:
maxKey = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey()
Map traversal examples
for (Map.Entry<Dog, Integer> entry : treeMap.entrySet()) { System.out.println(entry.getKey() + " - " + entry.getValue());}
Используя foreach из Java 8.
final long[] i = {0}; map.forEach((k, v) -> i[0] += k + v);
Используя keySet и foreach. Считается, что данный способ очень медленный, вопрос только на сколько.
long i = 0; for (Integer key : map.keySet()) { i += key + map.get(key); }
final long[] i = {0}; map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());
Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.putIfAbsent(i, "val" + i); } map.forEach((id, val) -> System.out.println(val));
putIfAbsent позволяет нам не писать дополнительные проверки на null; forEach принимает потребителя, который производит операцию над каждым элементом массива.
Этот код показывает как использовать для вычислений код при помощи различных функций:
map.computeIfPresent(3, (num, val) -> val + num); map.get(3); // val33 map.computeIfPresent(9, (num, val) -> null); map.containsKey(9); // false map.computeIfAbsent(23, num -> "val" + num); map.containsKey(23); // true map.computeIfAbsent(3, num -> "bam"); map.get(3); // val33
как удалить объект по ключу, только если этот объект ассоциирован с ключом:
map.remove(3, "val3"); map.get(3); // val33 map.remove(3, "val33"); map.get(3); // null
Еще один полезный метод: getOrDefault
map.getOrDefault(42, "not found"); // not found
Объединить записи двух массивов? Легко:
map.merge(9, "val9", (value, newValue) -> value.concat(newValue)); map.get(9); // val9 map.merge(9, "concat", (value, newValue) -> value.concat(newValue)); map.get(9); // val9concat
http://zeroturnaround.com/wp-content/uploads/2016/04/Java-Collections-cheat-sheet.png
http://www.beginnersbooktutorial.org/collections-framework-examples-programs-in-java-with-output/
http://tutorials.jenkov.com/java-collections/index.html
Collections class has a lot of static methods like sort, binarySearch, etc
Collections.sort(stringList, String.CASE_INSENSITIVE_ORDER);
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
Collections - много полезных статистических методов:
Для работы со списками:
static class Objects
https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html
Whenever method returns the collection, it is always better to return the empty
one instead of null return Collections.emptyList();
Arrays can store primitives and Objects; array is fixed size ; better performance
Collections can grow; collection can not store primitives (although they can store the primitive wrapper classes, such as Integer etc)
String[] array = { "foo", "bar" };List list = Arrays.asList( array );
Other direction - from List to Array:
namesList.toArray( new String[ namesList.size() ] );
Collections.unmodifiableList( namesList );
HashMap - not ordered by key
TreeMap TreeSet- sorted by key: insert, remove, delete ~logN
LinkedHashMap - FIFO order
Priority Queue http://www.eecs.wsu.edu/~ananth/CptS223/Lectures/heaps.pdf
http://www.programcreek.com/2013/02/leetcode-merge-k-sorted-lists-java/
public ListNode mergeKSortedLists(ListNode[] lists) { if(lists==null||lists.length==0) return null; PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(new Comparator<ListNode>(){ public int compare(ListNode l1, ListNode l2){ return l1.val - l2.val; } }); ListNode head = new ListNode(0); ListNode p = head; for(ListNode list: lists){ if(list!=null) queue.offer(list); } while(!queue.isEmpty()){ ListNode n = queue.poll(); p.next = n; p=p.next; if(n.next!=null) queue.offer(n.next); } return head.next;}
implemented as BST takes log(N) time for insert and delete(min)
min Binary heap is binary tree with 2 properties: order- for every node X
key(parent(X)) < key(X); hence min(key) always at root
insert and delete operations maintain the order
the height of BT is log(N)
Every level ecxept last is saturated
BT can be implemented as array:
left_chlild(i) = at [2i] right_chlild(i) = at [2i+1]
If there are N elements need to be put in heap it will take O(N*logN)
Collection works with reference types Map <String, String> hashMap = new HashMap<>(); Set <String> s = new HashSet < >(); SortedSet <String> cityNames = new TreeSet < >();
https://praveer09.github.io/technology/2016/06/21/writing-comparators-the-java8-way/
The Comparable interface consists of the following method:
public interface Comparable<T> {
public int compareTo(T o);
}
What if you want to sort some objects in an order other than their natural ordering? Or what if you want to sort some objects that don't implement Comparable? To do either of these things, you'll need to provide a Comparator — an object that encapsulates an ordering. Like the Comparable interface, the Comparator interface consists of a single method.
public interface Comparator<T> {
int compare(T o1, T o2);
}
Comparator
public static Comparator<String> compareInDirecton(int direction) {
return (x, y) -> direction * x.compareTo(y);
}
public static Comparator<String> reverse(Comparator<String> comp) {
return (x, y) -> comp.compare(x, y);
}
Arrays.sort(friends, compareInDirection(-1));
Arrays.sort(people, Comparator.comparing(Person::getName));
class LexicographicComparator implements Comparator<String> {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
class ByLengthComparator implements Comparator<String> {
public int compare(String o1, String o2) {
return Integer.compare(o1.length(), o2.length());
}
}
public class ComparatorExample {
public static void main(String[] args) {
List<String> fruits = Arrays.asList(
"watermelon",
"apple",
"pear");
Collections.sort(fruits, new LexicographicComparator());
// will print [apple, pear, watermelon]
System.out.println(fruits);
Collections.sort(fruits, new ByLengthComparator());
// will print [pear, apple, watermelon]
System.out.println(fruits);
}
}
http://blog.takipi.com/5-tips-for-reducing-your-java-garbage-collection-overhead/
http://www.slideshare.net/cnbailey/memory-efficient-java
for 32-bit JVM the object reference usually use 32-bit (= 4 bytes, same as int and float) as the size for object references, JVMs for 64-bit systems often use the native address size 64 bits (= 8 bytes) for object reference
size of references is equal to 4 bytes.
В java список — это List и 2 основные реализации:
первая — это ArrayList, поддерживает случайный доступ, в основе динамически расширяемого массива (увеличивается в полтора раза при заполнении), но при удалении элементов сам не сужается, для этого нужно вызывать предусмотренный метод (trimToSize).
вторая — LinkedList, двусвязный список последовательного доступа, размер ограничен только свободной памятью jvm. Хотя методы случайного доступа (по индексу) тоже присутствуют — как уже было сказано, они здесь выполняются за O(n)
Для использования списков в многопоточном окружении существует CopyOnWriteArrayList
(операции изменения — O(n)), обертки (synchonizedList) а также устаревший Vector.
Интерфейсы коллекций
List<String> strings = new ArrayList<>(); strings.stream().forEach((string) -> { System.out.println("Content: " + string); });
Chaining comparators
Arrays.sort(people, Comparator
.comparing(Person::getLastName)
.thenComparing(Person::getFirstName));
Comparator<User> userOrdering = Comparator
.comparing(User::isSubscription)
.thenComparing(User::getName);
// forward sort Collections.sort(users, userOrdering);
// reverse sort Collections.sort(users, userOrdering.reversed());
SORTING //Use Comparator object to perform custom sorting. SortedSet < City > sortedCitiesByName = new TreeSet < > ( Comparator.comparing(City::getName));
// Collections.sort
List<ObjectName> list = new ArrayList<ObjectName>();
Collections.sort(list, new Comparator<ObjectName>() {
public int compare(ObjectName o1, ObjectName o2) { return o1.toString().compareTo(o2.toString());
} });
If it is an array, use Arrays.sort() method:
ObjectName[] arr = new ObjectName[10]; Arrays.sort(arr, new Comparator<ObjectName>() { public int compare(ObjectName o1, ObjectName o2) { return o1.toString().compareTo(o2.toString());
} });
// TreeSet Set<ObjectName> sortedSet = new TreeSet<ObjectName>(new Comparator<ObjectName>() { public int compare(ObjectName o1, ObjectName o2) { return o1.toString().compareTo(o2.toString()); } }); sortedSet.addAll(unsortedSet);
If it is a map, use TreeMap to sort. TreeMap is sorted by key. // TreeMap - using String.CASE_INSENSITIVE_ORDER which is a Comparator that orders Strings by compareToIgnoreCase Map<String, Integer> sortedMap = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER); sortedMap.putAll(unsortedMap);
//TreeMap - In general, defined comparator Map<ObjectName, String> sortedMap = new TreeMap<ObjectName, String>(new Comparator<ObjectName>() { public int compare(ObjectName o1, ObjectName o2) { return o1.toString().compareTo(o2.toString()); } }); sortedMap.putAll(unsortedMap);
List <Account> accounts = Arrays.asList(new Account( 123), new Account( 456));
accounts.forEach( acc -> print( acc));
List<String> strings = new ArrayList<>(); for (String string : strings) { System.out.println("Content: " + string); }
...can be easily translated into a forEach statement:
Set, List, SortedSet, NavigableSet, Queue, Deque, BlockingQueue and BlockingDeque.
The other collection interfaces:
Map, SortedMap, NavigableMap, ConcurrentMap and ConcurrentNavigableMap
do not extend Collection, as they represent mappings rather than true collections. However, these interfaces contain collection-view operations, which allow them to be manipulated as collections.
Many of the modification methods in the collection interfaces are labeled optional. Some implementations may not perform one or more of these operations, throwing a runtime exception (UnsupportedOperationException) if they are attempted.
* — на самом деле, BitSet хоть и называется Set'ом, интерфейс Set не наследует.
Structures in JDK
http://habrahabr.ru/post/182776/
http://habrahabr.ru/company/luxoft/blog/256877/ Java Collections
Collections class: java.util.Collections
This class consists exclusively of static methods that operate on or return collections (sort, binarySearch, reverse,fill, copy, min, max,addAll, syncronizedCollection/List/Map,..)
Collections class contains static factories called synchronization wrappers that may be used to add synchronization to many unsynchronized collections
Collection interface http://java.sun.com/javase/6/docs/api/java/util/Collection.html
http://habrahabr.ru/post/129037/
http://habrahabr.ru/post/162017/
There are fourteen collection interfaces. The most basic interface is Collection. These interfaces extend Collection:
Collection interface is the parent of List, Queue and Set interfaces.
Java does not come with a usable implementation of the Collection interface, so you will have to use one of the listed subtypes
Maps such as HashMap are not Collections -they don’t implement the Collection interface.
keySet method of the Map interface returns a Set view of the Map object, consisting of all the keys in the map
WeakHashMap is useful then the desired lifetime of cache
entries is determined by external references to the key, not the value
Set -> SortedSet
Map -> SortedMap
interface: List - this is an ordered list of objects, insertion order is maintained and retrieval order is in the list order but items can also be random accessed, duplicate items are allowed, generally allow storage of null values (the ones below do), generally fast to iterate and find items by position but slow to do lookups
ArrayList - Unsychronized, nulls allowed (fastest)
Vector - Synchronized, only slightly slower in tests of sizes under 100000
Stack - Synchronized, same speed as Vector, LIFO queue
LinkedList - Unsynchronized, allows two way iteration and modification of items (like a stack or queue)
CopyOnWriteArrayList - Synchronized, significantly slower in tests of large numbers of items or average list changes, only slightly slower when used with very small numbers (<100)>
interface: Set - this a set of items with no duplicates (no two items can compare as equal), ordering is typically inconsistent over multiple set iterations depending on the implementation but you should assume the order is effectively random unless the set specifies ordered iteration, generally ok to iterate and fast to do lookups
HashSet - Unsychronized (fastest), slower than HashMap which it is built on, allows nulls
LinkedHashSet - Unsychronized, ordered by insertion, allows nulls
TreeSet - Unsychronized, ordered by the natural ordering of the items or a comparatorprovided at construction, allows nulls but there are issues with removing them
CopyOnWriteArraySet - Synchronized, significantly slower in tests of large numbers of items or average set changes, only slightly slower when used with very small numbers (<100)>
interface: Map - Stores key/value pairs (maps keys to values) where the keys must be unique, order of iteration over keys, values, or pairs is highly dependent on the implementation of the map, allowed nulls also vary by implementation, generally very fast to lookup keys and slow to lookup values
IdentityHashMap - Unsychronized (fastest), uses reference equality (==) instead of object equality (equals) to compare keys, actually violates the Map interface guarantee, all iterators are unordered, allows null keys and values
HashMap - Unsychronized, this is the fastest general purpose map, all iterators are unordered, allows null keys and values
ConcurrentHashMap - Synchronized, all iterators are unordered, does not allow null keys or values
Hashtable - Synchronized, all iterators are unordered, does not allow null keys or values
LinkedHashMap - Unsychronized, all iterators are ordered based on insertion order of the original key (does not change if a key is reinserted), allows null values but null keys are not allowed
TreeMap - Unsychronized, iterators are ordered by the natural or comparator ordering of the keys, allows null keys and values but the comparator needs to understand them
ArrayList is fast as long as you know the size in advance (or as long as you don’t have many resizing) and as long as you don’t have many removals. On the other hand there are memory considerations – LinkedList has the pointers overhead but a large ArrayList might require a big chunk of contiguous memory to be allocated on a resize operation, also a large empty ArrayList is a big waste of memory.
Same for CopyOnWriteArrayList – the performance issue in here is also depending on the usage: modification of the list might cost (it is synchronized and allocates a new list) however it is very efficient for concurrent iteration and you are safe from the concurrent modification exception.
MAPS
// key list
List keyList = new ArrayList(map.keySet());
// value list
List valueList = new ArrayList(map.values());
// key-value list
List entryList = new ArrayList(map.entrySet());
https://www.reddit.com/r/programming/comments/59qgyf/did_you_know_java_8_hashmap_automatically/
http://coding-geek.com/how-does-a-hashmap-work-in-java/
What is a HashMap.Entry?
It contains a key, a value, int hash of a key and a pointer to the next entry
It means that an entry occupies 32 bytes = (12 bytes header + 16 bytes data (8 key and 8 value) + 4 bytes padding).
Hence HashMap with size = S has to spend 32 * S bytes for entries storage. Besides, it will use 4 * C bytes for entries array, where C is the map capacity (here 4 is the size of object reference in bytes on 32 bits VM).
Map traversing
for(Map.Entry mapEntry : map.entrySet()) { //this is fast
Key key = mapEntry.getKey();
Value value = mapEntry.getValue();
}
for (Key key : map.keySet()) { //this is slow
Value value = map.get(key);
}
// a method for getting key of a target value
public Character getKey(HashMap<Character,String> map, String target){ for (Map.Entry<Character,String> entry : map.entrySet()) {
if (entry.getValue().equals(target)) {
return entry.getKey();
} }
return null;
}
Prints a frequency table of the words on the command line
public class Frequency { public static void main(String[] args) {
Map<String, Integer> m = new TreeMap<String, Integer>();
for (String word : args) {
Integer freq = m.get(word);
m.put(word, (freq == null ? 1 : freq + 1));
}
System.out.println(m);
}
}
Map interface provides three collection views:
Set keySet(): Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
Collection values(): Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
Set<Map.Entry<K, V>> entrySet(): Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
LinkedHashMap
The removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.
Map<String, Integer> counts = new HashMap<>();
counts.put(“Alice”, 1); // Adds the key/value pair to the map
counts.put(“Alice”, 2); // Updates the value for the key
This example uses a hash map which, as for sets, is usually the better choice if you don’t
need to visit the keys in sorted order. If you do, use a TreeMap instead.
Here is how you can get the value associated with a key:
int count = counts.get(“Alice”);
If the key isn’t present, the get method returns null. In this example, that would cause a
NullPointerException when the value is unboxed. A better alternative is
int count = counts.getOrDefault(“Alice”, 0);
Then a count of 0 is returned if the key isn’t present.
When you update a counter in a map, you first need to check whether the counter is
present, and if so, add 1 to the existing value. The merge method simplifies that common
operation. The call
counts.merge(word, 1, Integer::sum);
associates word with 1 if the key wasn’t previously present, and otherwise combines the
previous value and 1, using the Integer::sum function.
Sometimes, you want to share the contents of a collection but you don’t want it to be
modified. Of course, you could copy the values into a new collection, but that is
potentially expensive. An unmodifiable view is a better choice. Here is a typical situation.
A Person object maintains a list of friends. If the getFriends gave out a reference to
that list, a caller could mutate it. But it is safe to provide an unmodifiable list view:
public class Person {
private ArrayList<Person> friends;
public List<Person> getFriends() {
return Collections.unmodifiableList(friends);
}
…
}
All mutator methods throw an exception when they are invoked on an unmodifiable view.
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
String k = entry.getKey();
Integer v = entry.getValue();
Process k, v
}
Or simply use the forEach method:
counts.forEach((k, v) -> {
public void process(String directions) {
this.directions = Objects.requireNonNull(directions);
…
}
List<String> list = new ArrayList<String>(c)
public class MovieComparator implements Comparator<movie>{
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
13
14
15
16
17
18
19
20
@Override
public int compare(Movie movie1, Movie movie2) {
int rank1 = movie1.getRank();
int rank2 = movie2.getRank();
if (rank1 > rank2){
return +1;
}else if (rank1 < rank2){
return -1;
}else{
return 0;
}
}
}
List<movie> movies = new ArrayList<movie>();
movies.add(new Movie("Harry Potter", 3));
movies.add(new Movie("Transformer", 4));
movies.add(new Movie("True Lies", 1));
movies.add(new Movie("Rush Hour- III", 2));
movies.add(new Movie("Golden Eye", 5));
MovieComparator comparator = new MovieComparator();
Collections.sort(movies, comparator);
Sort Map by value
static Map sortByValue(Map map) {
List list = new LinkedList(map.entrySet());
Collections.sort(list,
new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
}
}
);
Map result = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
} //end of sortByValue
/*********************************************** * Sort a map by values * * @param map Unsorted map * @return Sorted map ***********************************************/ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); Map<K, V> result = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; }
Predicates
public interface Predicate<T> {
boolean test(T t);
// Additional default and static methods
}
public interface Closeable {
void close();
}
list.forEach(System.out::println);
The ArrayList class has a removeIf method whose parameter is a Predicate. It is
specifically designed to pass a lambda expression. For example, the following statement
removes all null values from an array list:
list.removeIf(e -> e == null);
Alternative Java collections
http://code.google.com/p/guava-libraries/
http://code.google.com/p/google-collections/
http://labs.carrotsearch.com/hppc.html
http://javolution.org/
http://trove4j.sourceforge.net/ http://labs.carrotsearch.com/hppc.html
http://pcj.sourceforge.net/ http://sites.google.com/site/glazedlists/Home
http://code.google.com/p/flatmap/ http://high-scale-lib.sourceforge.net/
Java Collections needs more than three times the memory compared to the primitive collection frameworks.
http://marxsoftware.blogspot.com/2016/01/fastutil-java-collections.html
https://www.reddit.com/r/java/comments/4067ne/lgpl_gnu_trove_high_performance_collections_for/