# Notes
# Collections
A Collection is a group of individual objects represented as a single unit.
集合是一组表示为单个单元的单个对象。
Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.
Java 提供了 Collection Framework,它定义了几个类和接口,来将一组对象表示为单个单元。
- Collection 集合
- Root interface with basic methods like
add()
,remove()
,contains()
,isEmpty()
,addAll()
, ... etc.
带有基本方法的根接口 - Set
- Doesn't allow duplicates.
不允许重复。 - List
- Can contain duplicates and elements are ordered.
可以包含重复项,并且元素是有序的。 - Queue 队列
- Typically order elements in FIFO order.
通常以 FIFO 顺序对元素进行排序
# Some cool applicabilities using Collections
sorting | shuffle |
reversing | binarySearch |
auto copy | rotate (shift elements by distance) |
frequency counter | |
comparing | |
lambdas |
# SORTS 排序
// Java program to demonstrate working of Collections.sort() | |
import java.util.*; | |
public class CollectionTest { | |
public static void main(String[] args) { | |
// Create a list of strings | |
ArrayList<String> trendList = new ArrayList<String>(); | |
trendList.add("data science"); | |
trendList.add("digital forensics"); | |
trendList.add("cloud computing"); | |
/* Collections.sort method is sorting the | |
elements of ArrayList in ascending order. */ | |
Collections.sort(trendList); | |
// Let us print the sorted list | |
System.out.println("List after the use of" + | |
" Collection.sort() :\n" + trendList); | |
} | |
} |
Output:
List after the use of Collection.sort() :
[cloud computing, data science, digital forensics]
// Java program to demonstrate working of Collections.reverse() | |
public static void main(String[] args) { | |
// :: | |
Collections.sort(trendList); | |
Collections.reverse(trendList); | |
// Let us print the sorted list | |
System.out.println("List after the use of" + | |
" Collection.sort() :\n" + trendList); | |
} |
Output:
List after the use of Collection.reverse() :
[digital forensics, data science, cloud computing]
# AUTOCOPY (n copies)
// Create copies of some objects. | |
List list = Collections.nCopies(4, "Java Power"); | |
// Displaying the list returned | |
System.out.println("The list returned is :"); | |
Iterator itr = list.iterator(); | |
while (itr.hasNext()) { | |
System.out.print(itr.next() + " "); | |
} | |
System.out.println("\n"); |
Output:
The list returned is :
Java Power Java Power Java Power Java Power
# FREQUENCY COUNTER
// count the frequency of the words "data science" | |
System.out.println("The frequency of the word data science is: " + | |
Collections.frequency(trendList, "data science")); |
Output:
The frequency of the word data science is: 1
# COMPARATORS
Interface allows multiple sorting sequences (ex. Name, id, and price, etc.)
Uses
compare()
method to sort elementscompare()
takes 2 elements as argumentspublic int compare(Object obj1, Object obj2)
Comparator is found in
java.util
package.
# Action plan
- Create a class to implement the interface
- Use
Arrays.sort
to sort the class objects
class Dog { | |
int size, weight; | |
public Dog(int s, int w){ | |
size = s; | |
weight = w; | |
} | |
} | |
class DogSizeComparator implements Comparator<Dog> { | |
@Override | |
public int compare(Dog o1, Dog o2) { | |
return o1.size - o2.size; | |
} | |
} | |
class DogWeightComparator implements Comparator<Dog> { | |
public int compare(Dog o1, Dog o2) { | |
return o1.weight - o2.weight; | |
} | |
} | |
public class ArraySort { | |
public static void main(String[] args) { | |
Dog d1 = new Dog(2, 50); | |
Dog d2 = new Dog(1, 30); | |
Dog d3 = new Dog(3, 40); | |
Dog[] dogArray = {d1, d2, d3}; | |
printDogs(dogArray); | |
Arrays.sort(dogArray, new DogSizeComparator()); | |
printDogs(dogArray); | |
Arrays.sort(dogArray, new DogWeightComparator()); | |
printDogs(dogArray); | |
} | |
public static void printDogs(Dog[] dogs){ | |
for(Dog d: dogs) | |
System.out.print("size="+d.size + " weight=" + | |
d.weight + " "); | |
System.out.println(); | |
} | |
} |
Output:
size=2 weight=50 size=1 weight=30 size=3 weight=40
size=1 weight=30 size=2 weight=50 size=3 weight=40
size=1 weight=30 size=3 weight=40 size=2 weight=50
# Queue Interface
The Queue interface is available in java.util
package and extends the Collection interface.
Queue 接口在 java.util
包中可用,并且扩展了 Collection 接口。
The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc.
队列集合用于保存将要处理的元素,并提供各种操作,如插入,删除等。
It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle.
它是对象的有序列表,其使用仅限于在列表末尾插入元素,并从头开始删除元素,即遵循 FIFO 或先进先出原则。
import java.util.LinkedList; | |
import java.util.Queue; | |
public class QueueExample { | |
public static void main(String[] args) { | |
Queue<Integer> q = new LinkedList<>(); | |
// Adds elements {0, 1, 2, 3, 4} to queue | |
for (int i=0; i<5; i++) | |
q.add(i); | |
// Display contents of the queue. | |
System.out.println("Elements of queue-"+q); | |
// To remove the head of queue. | |
int removedele = q.remove(); | |
System.out.println("removed element-" + removedele); | |
System.out.println(q); | |
// To view the head of queue | |
int head = q.peek(); | |
System.out.println("head of queue-" + head); | |
//Show queue size | |
int size = q.size(); | |
System.out.println("Size of queue-" + size); | |
} | |
} |
# Map Interface
- Map
- general key/value
map interface - HashMap
- most widely
used Map
HashMap does not allow duplicate keys however it allows to have duplicate values.
import java.util.Collection; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.Set; | |
Map<String, String> states = new HashMap<String, String>(); | |
// store values in map | |
states.put("ca", "California"); | |
states.put("az", "Arizona"); | |
states.put("mn", "Minnesota"); | |
states.put("nj", "New Jersey"); | |
// retrieve values from map | |
states.get("ca"); // returns "California" | |
states.get("nj"); // returns "New Jersey" | |
// Pull out live Collection of all the values. | |
Collection<String> values = states.values(); | |
System.out.println(values); // [Minnesota, New Jersey,… Arizona] | |
// Use keySet to pull out live set of the keys -- use to print key->value for the whole map. | |
// The order of the keys is random for a HashSet. | |
Set<String> keys = states.keySet(); | |
for (String key:keys) { | |
System.out.println(key + "->" + states.get(key)); | |
} |
Output:
mn->Minnesota
nj->New Jersey
ca->The Golden State
az->Arizona