# How can Java be used to extract all repeated values from multiple lists?

edit retag close merge delete

Sort by ยป oldest newest most voted

One way to extract all repeated values from multiple lists in Java is to use a HashMap to keep track of the occurrence of each element in the lists.

Steps: 1. Initialize a HashMap to keep track of the occurrence of each element in the lists. 2. Loop through each list and for each element, check if it already exists in the HashMap. 3. If the element already exists in the HashMap, increment its count by 1. 4. If the element does not exist in the HashMap, add it with a count of 1. 5. After looping through all the lists, loop through the HashMap and extract all elements whose count is greater than 1, indicating that the elements are repeated in multiple lists.

Here's a sample code to extract all repeated values from multiple lists:

import java.util.*;

public class RepeatedValues {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6);
List<Integer> list3 = Arrays.asList(5, 6, 7, 8);

Map<Integer, Integer> countMap = new HashMap<>();

// Loop through all the lists and count the occurrence of each element using HashMap
for (Integer i : list1) {
countMap.put(i, countMap.getOrDefault(i, 0) + 1);
}
for (Integer i : list2) {
countMap.put(i, countMap.getOrDefault(i, 0) + 1);
}
for (Integer i : list3) {
countMap.put(i, countMap.getOrDefault(i, 0) + 1);
}

// Loop through the HashMap and extract all elements whose count is greater than 1
Set<Integer> repeatedValues = new HashSet<>();
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
if (entry.getValue() > 1) {
}
}

System.out.println("Repeated values: " + repeatedValues); // Output: Repeated values: [3, 4, 5, 6]
}
}

more