forked from angiejones/java-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectionsDemo.java
More file actions
96 lines (75 loc) · 2.64 KB
/
Copy pathCollectionsDemo.java
File metadata and controls
96 lines (75 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package chapter12;
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args){
setDemo();
listDemo();
queueDemo();
mapDemo();
}
public static void setDemo(){
Set fruit = new HashSet();
fruit.add("apple");
fruit.add("lemon");
fruit.add("banana");
fruit.add("orange");
fruit.add("lemon");
System.out.println(fruit.size()); //4
System.out.println(fruit); //[banana, orange, apple, lemon]
}
public static void listDemo(){
List fruit = new ArrayList();
fruit.add("apple");
fruit.add("lemon");
fruit.add("banana");
fruit.add("orange");
fruit.add("lemon");
System.out.println(fruit.get(2)); //banana
System.out.println(fruit.size()); //5
System.out.println(fruit); //[apple, lemon, banana, orange, lemon]
}
public static void queueDemo(){
Queue fruit = new LinkedList();
fruit.add("apple");
fruit.add("lemon");
fruit.add("banana");
fruit.add("orange");
fruit.add("lemon");
System.out.println(fruit.size()); //5
System.out.println(fruit); //[apple, lemon, banana, orange, lemon]
fruit.remove();
System.out.println(fruit);//[lemon, banana, orange, lemon]
System.out.println(fruit.peek());//lemon
}
public static void mapDemo(){
Map fruitCalories = new HashMap();
fruitCalories.put("apple", 95);
fruitCalories.put("lemon", 20);
fruitCalories.put("banana", 105);
fruitCalories.put("orange", 45);
fruitCalories.put("lemon", 17);
System.out.println(fruitCalories.size()); //4
System.out.println(fruitCalories); //{banana=105, orange=45, apple=95, lemon=17}
System.out.println(fruitCalories.get("lemon"));//17
System.out.println(fruitCalories.entrySet());//[banana=105, orange=45, apple=95, lemon=17]
fruitCalories.remove("orange");
System.out.println(fruitCalories);//{banana=105, apple=95, lemon=17}
}
public void print(Collection<String> collection){
var i = collection.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
for(String item : collection){
System.out.println(item);
}
collection.forEach(System.out::println);
}
public void print(Map<String, Integer> map){
for(var entry : map.entrySet()){
System.out.println(entry.getValue());
}
map.forEach(
(k,v)->System.out.println("Fruit: " + k + ", Calories: " + v));
}
}