Java Collection: Using Collections API


Common Collections Utils
Collections.sort(), max(), min(), .reverse(), shuffle(),rotate()
Collections.swap(),fill(), copy(),replaceAll(),
return Collections.emptyList(), unmodifiabkeList(), synchronizedList(),checkedList()

Collections.disjoint(c1,c2) -- return number of common elements
Collections.frequency(c, obj) -- how many times the element appears. 
Collections.nCopies(n, T) -- better performance

Collections.reverseOrder() -- returns a comparator that do reverse of that natural ordering
Collections.reverseOrder(Comparator cmp)
Use ListIterator
 ArrayList<Integer> arr = new ArrayList<Integer>();
  ListIterator<Integer> listIt = arr.listIterator();
 while(listIt.hasPrevious())
 {
  Integer i = listIt.previous();
  int idx = listIt.previousIndex();
 }
 
 LinkedList<Integer> list = new LinkedList<>();
 listIt = list.listIterator();
 
 // or use descendingIterator
 Iterator<Integer> descIt = list.descendingIterator();

Collections.rotate - left rotate
 LinkedList<Integer> list = Arrays.asList(0,1,2,3,4);
 LinkedList<Integer> newList = new LinkedList<>(list);
 Collections.rotate(newList, 1);
 System.out.println(newList); // [4, 0, 1, 2, 3]
 newList = new LinkedList<>(list);
 //Collections.rotate(newList, -1);/[1, 2, 3, 4, 0]
 System.out.println(newList);

Collections.binarySearch
If there are multiple elements equal to the specified object in the sorted list, there is no guarantee which one will be found. If we want to always return the first or last element, write our own binarySearch implementation.

Union of two Collections:
list1.addAll(list2)

Intersection of two Collections:
list1.retainAll(list2)

Difference between two Collections
list1.removeAll(list2)

Collections.API Usage
List<Integer> list = Collections.nCopies(10, -1);
// this will throws java.lang.UnsupportedOperationException
// list.add(-11);

list = new ArrayList<>(Collections.nCopies(10, -1));
list.add(-11);

// list is still 0 length
Collections.fill(list, -1);

// add them to the list
Collections.addAll(list, 1, 1, 1, 1, 1);
Caveat: Can't add or remove element into the list returned by Arrays.asList
The return type is private static inner class: java.util.Arrays.ArrayListWe can iterate, get or change(set) existing elment, but can't not add or remove elements, which will throw UnsupportedOperationException.

Caveat: Don't use primitive array as parameter of Arrays.asList
It actually puts the whole primitive array as the first element in the result list. From the following example, the result list type is List<int[]> not List<Integer> .
List<int[]> list = Arrays.asList(new int[] { 0, 1, 2, 3, 4 }); 
System.out.println(list); //[[I@45ff54e6]
System.out.println(list.size()); //1
System.out.println(list.get(0).getClass()); //class [I
System.out.println(list.get(0));//[I@45ff54e6

Using Guava Ints.asList to convert int[] to List
When we want to convert primitive array to it's List of wrapper type, and don't want to write the loop, we can use Guava's primitive utils: Ints, Longs, Doubles and etc.
int maxValue = Collections.max(Ints.asList(intArray));

Equality for Collection
Collection determines equality by content: They are same as long as two lists belong to same interface(List, Set) and have same elements.
List<Integer> arr = new ArrayList<>();
arr.add(1);
List<Integer> list = new LinkedList<>();
list.add(1);
assertTrue(arr.equals(list));

Set<Integer> hashSet = new HashSet<>();
hashSet.add(1);

Set<Integer> treeSet = new TreeSet<>();
treeSet.add(1);
assertTrue(hashSet.equals(treeSet));

Performance
Using LinkedList when add or remove elements frequently

In Single thread application, when iterate ArrayList in performance-critical section, consider using for-get to loop elements in stead of using for-loop or iterator> This can avoid the unnecessary concurrent modification check.

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)