Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions src/main/java/Collections/Practice/CollectionBasics.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package Collections.Practice;

import java.util.ArrayList;
import java.util.Collection;
import java.util.*;

public class CollectionBasics {
public static void main(String[] args) {
Expand Down Expand Up @@ -33,7 +32,9 @@ public static int sum(Collection<Integer> numbers) {
// TODO:
// Loop through the collection
// Add each number to total

for(int num: numbers) {
total += num;
}
return total;
}

Expand All @@ -50,6 +51,11 @@ public static int countEven(Collection<Integer> numbers) {
// Loop through the collection
// If the number is even, increase count

for(int num: numbers) {
if(num % 2 == 0) {
count++;
}
}
return count;
}

Expand All @@ -66,6 +72,11 @@ public static int findMax(Collection<Integer> numbers) {
// Loop through numbers
// Update max if current number is larger

for(int num: numbers) {
if(num > max) {
max = num;
}
}
return max;
}

Expand All @@ -80,6 +91,14 @@ public static boolean hasDuplicates(Collection<Integer> numbers) {
// TODO:
// Hint:
// Compare the size of a collection with the size of a Set
HashSet<Integer> set = new HashSet<>();

for(int num: numbers) {
//if false, then return true
if(!set.add(num)) {
return true;
}
}

return false;
}
Expand All @@ -97,6 +116,9 @@ public static int countOccurrences(Collection<Integer> numbers, int target) {
// Loop through numbers
// If number equals target, increase count

for(int num : numbers) {
if(num == target) count++;
}
return count;
}

Expand All @@ -114,6 +136,14 @@ public static Collection<Integer> filterGreaterThanTwenty(Collection<Integer> nu
// Loop through numbers
// Add numbers greater than 20 to result

Iterator<Integer> iterator = numbers.iterator();

while (iterator.hasNext()) {
int element = iterator.next();
if (element > 20) {
result.add(element);
}
}
return result;
}
}
Loading