-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathCollectionBasics.java
More file actions
119 lines (91 loc) · 2.54 KB
/
CollectionBasics.java
File metadata and controls
119 lines (91 loc) · 2.54 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package Collections.Practice;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
public class CollectionBasics {
public static void main(String[] args) {
Collection<Integer> numbers = new ArrayList<>();
numbers.add(4);
numbers.add(8);
numbers.add(15);
numbers.add(16);
numbers.add(23);
numbers.add(42);
System.out.println("Sum of numbers: " + sum(numbers));
System.out.println("Count of even numbers: " + countEven(numbers));
System.out.println("Largest number: " + findMax(numbers));
System.out.println("Contains duplicates? " + hasDuplicates(numbers));
}
/*
PROBLEM 1
Return the sum of all numbers in the collection
*/
public static int sum(Collection<Integer> numbers) {
int total = 0;
for (Integer num : numbers) {
total += num;
}
return total;
}
/*
PROBLEM 2
Count how many numbers are even
*/
public static int countEven(Collection<Integer> numbers) {
int count = 0;
for (Integer num : numbers) {
if (num % 2 == 0) {
count++;
}
}
return count;
}
/*
PROBLEM 3
Find the largest number in the collection
*/
public static int findMax(Collection<Integer> numbers) {
int max = Integer.MIN_VALUE;
for (Integer num : numbers) {
if (num > max) {
max = num;
}
}
return max;
}
/*
PROBLEM 4
Return true if the collection contains duplicates
Return false otherwise
*/
public static boolean hasDuplicates(Collection<Integer> numbers) {
return numbers.size() != new HashSet<>(numbers).size();
}
/*
PROBLEM 5
Count how many times a target value appears
*/
public static int countOccurrences(Collection<Integer> numbers, int target) {
int count = 0;
for (Integer num : numbers) {
if (num == target) {
count++;
}
}
return count;
}
/*
BONUS PROBLEM
Create and return a new collection
that only contains numbers greater than 20
*/
public static Collection<Integer> filterGreaterThanTwenty(Collection<Integer> numbers) {
Collection<Integer> result = new ArrayList<>();
for (Integer num : numbers) {
if (num > 20) {
result.add(num);
}
}
return result;
}
}