0% found this document useful (0 votes)
14 views3 pages

Java Collections: Remove Duplicates & Count

The document outlines five Java tasks related to collections. Task 1 involves removing duplicates from a list using HashSet, Task 2 counts occurrences of strings with HashMap, Task 3 generates random numbers, Task 4 checks for word occurrences in a map, and Task 5 prints all entries from a HashMap. Each task includes example code and test cases to demonstrate functionality.

Uploaded by

Judith Nelson
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views3 pages

Java Collections: Remove Duplicates & Count

The document outlines five Java tasks related to collections. Task 1 involves removing duplicates from a list using HashSet, Task 2 counts occurrences of strings with HashMap, Task 3 generates random numbers, Task 4 checks for word occurrences in a map, and Task 5 prints all entries from a HashMap. Each task includes example code and test cases to demonstrate functionality.

Uploaded by

Judith Nelson
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Collections Tasks Based on PPT

Task 1: Remove Duplicates Using HashSet


Write a method that takes a list of integers and removes any duplicate values.
Use a HashSet to remove the duplicates. Make sure to return the result as a new list,
preserving the original order of the elements in the input list.

Example:
```java
import [Link].*;

public class RemoveDuplicates {


public static List<Integer> removeDuplicates(List<Integer> inputList) {
Set<Integer> set = new HashSet<>(inputList); // removes duplicates
return new ArrayList<>(set);
}
}
```
Test Case:
```java
List<Integer> inputList = [Link](1, 2, 2, 3, 4, 4, 5);
[Link](removeDuplicates(inputList)); // Output: [1, 2, 3, 4, 5]
```

Task 2: Counting Occurrences Using HashMap


Write a method that takes a list of strings and counts how many times each string appears.
Use a HashMap where the keys are the strings, and the values are the counts. Ensure the
method handles an empty list correctly.

Example:
```java
import [Link].*;

public class CountOccurrences {


public static Map<String, Integer> countOccurrences(List<String> words) {
Map<String, Integer> map = new HashMap<>();
for (String word : words) {
[Link](word, [Link](word, 0) + 1);
}
return map;
}
}
```
Test Case:
```java
List<String> words = [Link]("apple", "banana", "apple", "orange", "banana",
"banana");
[Link](countOccurrences(words)); // Output: {apple=2, banana=3, orange=1}
```

Task 3: Generate Random Numbers Using Random Class


Write a method that generates a random number between 1 and 100 using the Random
class.
Ensure that each time the method is called, it returns a different number.

Example:
```java
import [Link].*;

public class GenerateRandom {


public static int generateRandomNumber() {
Random rand = new Random();
return [Link](100) + 1; // generates a number between 1 and 100
}
}
```
Test Case:
```java
[Link](generateRandomNumber()); // Output: random number between 1 and
100
```

Task 4: Checking if a Word is in the Map


Write a method that checks if a word is in the HashMap created in the previous task.
If the word exists, return the count of occurrences, otherwise return 0.

Example:
```java
import [Link].*;

public class CheckWordInMap {


public static int checkWord(Map<String, Integer> map, String word) {
return [Link](word, 0);
}
}
```
Test Case:
```java
Map<String, Integer> map = countOccurrences([Link]("apple", "banana", "apple"));
[Link](checkWord(map, "banana")); // Output: 1
[Link](checkWord(map, "cherry")); // Output: 0
```

Task 5: Print All Entries from HashMap


Write a method that prints out all entries in the HashMap, showing each word and its
corresponding count.

Example:
```java
import [Link].*;

public class PrintEntries {


public static void printEntries(Map<String, Integer> map) {
for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + ": " + [Link]());
}
}
}
```
Test Case:
```java
Map<String, Integer> map = countOccurrences([Link]("apple", "banana", "apple"));
printEntries(map);
// Output:
// apple: 2
// banana: 1
```

Common questions

Powered by AI

The `getOrDefault` method is preferred over traditional if-else checks for accessing map values in Java as it simplifies code readability and reduces potential errors in performance-critical applications. It retrieves a value associated with a specified key or returns a default if the key is not present, combining lookup and default logic into a single, efficient operation, thus optimizing performance by minimizing conditional checks and enhancing code conciseness. This idiomatic approach is especially beneficial when default values are frequently required, as it eliminates redundant checks and improves the maintainability and legibility of the code .

LinkedHashSet should be used instead of HashSet when preserving the order of elements while removing duplicates because it maintains a doubly linked list running through all of its entries, ensuring that iteration occurs in insertion order. This affects implementation by allowing developers to directly convert a list into a LinkedHashSet to remove duplicates without losing the order of elements, which is particularly important in applications where sequence is important (e.g., maintaining chronological data input). An example implementation is shown here: ```java import java.util.*; public class RemoveDuplicates { public static List<Integer> removeDuplicates(List<Integer> inputList) { Set<Integer> set = new LinkedHashSet<>(inputList); return new ArrayList<>(set); } } ``` .

The Random class in Java is particularly advantageous when generating multiple random values due to its efficient design for pseudorandom number generation across JVM sessions, producing values with a uniform distribution. It offers methods such as `nextInt`, `nextDouble`, and `nextLong` for different data types, providing flexibility in generating various types of random numbers. Compared to methods like `Math.random()`, which returns a double, Random can generate integers directly and is instantiated once for generating multiple numbers, making it more resource-efficient. However, for more demanding applications requiring high unpredictability, one might consider `SecureRandom` instead .

A Java method to print all entries in a HashMap can be constructed by iterating over `entrySet()` of a HashMap, which provides a set view of the mappings contained in the map. Using a for-each loop, each entry's key and value can be accessed and printed. The following method demonstrates this: ```java import java.util.*; public class PrintEntries { public static void printEntries(Map<String, Integer> map) { for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } } ``` This functionality is useful in scenarios such as debugging, logging data processes, and generating user-readable reports that provide transparency of data operations .

When using Java's HashMap for managing large datasets of word occurrences, potential pitfalls include excessive memory consumption and inefficient resizing operations if initial capacity is not properly estimated. High hash collisions can degrade performance to linear time. Best practices involve setting an appropriate initial capacity and load factor to minimize resizing overhead. Ensuring good hash code distribution can reduce collisions. Using `LinkedHashMap` can preserve the order of insertion, which might be required for certain operations. Moreover, considering thread-safe alternatives like `ConcurrentHashMap` is crucial when dealing with concurrent modifications .

Using Java's Random class for generating randomness within a bounded range introduces challenges in deterministic testing since it generates different sequences on each run unless seeded. This randomness complicates reproducibility, essential in testing environments. However, by initializing the Random class with a fixed seed, developers can produce consistent sequences, thus enabling deterministic testing. This controlled random behavior ensures reproducibility without altering the logic requiring randomness, hence balancing between testing needs and operational requirements. Such an approach is often used in test suites to verify outcomes dependent on stochastic processes while maintaining consistency across test executions .

The method to remove duplicate integers from a list in Java while preserving the original order involves using a LinkedHashSet. The LinkedHashSet maintains insertion order, unlike a HashSet, which ensures that elements appear in the order they were inserted into the set, effectively maintaining the order from the input list. The procedure involves initially converting the list to a LinkedHashSet to remove duplicates and then converting it back to a list. Example: ```java import java.util.*; public class RemoveDuplicates { public static List<Integer> removeDuplicates(List<Integer> inputList) { Set<Integer> set = new LinkedHashSet<>(inputList); return new ArrayList<>(set); } } ``` In this way, duplicates are eliminated, and order is preserved .

In Java, counting occurrences of strings in a list using HashMap is achieved by iterating over the list and incrementing the value for each string key in the map. If the string is not already a key, it is added to the map with a count of 1. This approach allows efficient O(1) average-time complexity for both insertions and updates, making it excellent for counting as all operations are performed in constant time relative to the number of strings. Here is the code used in such situations: ```java import java.util.*; public class CountOccurrences { public static Map<String, Integer> countOccurrences(List<String> words) { Map<String, Integer> map = new HashMap<>(); for (String word : words) { map.put(word, map.getOrDefault(word, 0) + 1); } return map; } } ``` The efficiency of HashMap operations significantly improves processing large datasets .

Using a HashMap in Java for checking the existence of a word is highly efficient due to its average time complexity of O(1) for get and containsKey operations. This efficiency stems from its internal use of a hash table data structure, which allows direct access to values using keys with minimal collision handling. In contrast, other data structures like lists would require O(n) time complexity for searching elements, as they would involve a linear search. Here's how a word can be checked for existence: ```java public class CheckWordInMap { public static int checkWord(Map<String, Integer> map, String word) { return map.getOrDefault(word, 0); } } ``` Thus, HashMap offers a significant performance advantage in applications requiring frequent searches .

In Java, the `Random` class should be used to generate random numbers within a specific range. By utilizing `Random.nextInt(100) + 1;`, it generates numbers between 1 and 100. The method `nextInt(n)` from `Random` generates a uniformly distributed pseudorandom integer within the specified range, here (from 0 to n-1), hence adding 1 shifts the range to (1 to 100). This method is effective because it provides a simple and direct means to generate random numbers with robust support across Java applications. An example implementation is: ```java import java.util.*; public class GenerateRandom { public static int generateRandomNumber() { Random rand = new Random(); return rand.nextInt(100) + 1; } } ``` .

You might also like