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
44 changes: 35 additions & 9 deletions src/main/java/Collections/Practice/CollectionBasics.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package Collections.Practice;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class CollectionBasics {
public static void main(String[] args) {
Expand All @@ -19,6 +22,7 @@ public static void main(String[] args) {
System.out.println("Count of even numbers: " + countEven(numbers));
System.out.println("Largest number: " + findMax(numbers));
System.out.println("Contains duplicates? " + hasDuplicates(numbers));
System.out.println("Numbers greater than 20: " + filterGreaterThanTwenty(numbers));
}


Expand All @@ -33,6 +37,9 @@ public static int sum(Collection<Integer> numbers) {
// TODO:
// Loop through the collection
// Add each number to total
for(Integer number: numbers){
total += number;
}

return total;
}
Expand All @@ -49,7 +56,11 @@ public static int countEven(Collection<Integer> numbers) {
// TODO:
// Loop through the collection
// If the number is even, increase count

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

Expand All @@ -65,6 +76,11 @@ public static int findMax(Collection<Integer> numbers) {
// TODO:
// Loop through numbers
// Update max if current number is larger
for(Integer number: numbers){
if(max < number){
max = number;
}
}

return max;
}
Expand All @@ -76,15 +92,17 @@ public static int findMax(Collection<Integer> numbers) {
Return false otherwise
*/
public static boolean hasDuplicates(Collection<Integer> numbers) {

// TODO:
// Hint:
// Compare the size of a collection with the size of a Set
List<Integer> seen = new ArrayList<>();
for (Integer num : numbers) {
if (seen.contains(num)) {
return true;
}
seen.add(num);
}

return false;
}


/*
PROBLEM 5
Count how many times a target value appears
Expand All @@ -96,7 +114,11 @@ public static int countOccurrences(Collection<Integer> numbers, int target) {
// TODO:
// Loop through numbers
// If number equals target, increase count

for (Integer number: numbers){
if(number == target){
count++;
}
}
return count;
}

Expand All @@ -112,8 +134,12 @@ public static Collection<Integer> filterGreaterThanTwenty(Collection<Integer> nu

// TODO:
// Loop through numbers
// Add numbers greater than 20 to result

// Add numbers greater than 20 to result\
for (Integer number:numbers){
if (number > 20) {
result.add(number);
}
}
return result;
}
}
Loading