Created
January 21, 2024 09:09
-
-
Save mahenzon/23e6070184addffb9e4320495dc02e35 to your computer and use it in GitHub Desktop.
Java example dictionary with "default" HashSet of integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String[] args) { | |
int[] numbers = {1, 2, 3, 2, 4, 5, 3, 6, 7, 4}; | |
HashMap<Integer, HashSet<Integer>> dictionary = new HashMap<>(); | |
for (int i = 0; i < numbers.length; i++) { | |
int number = numbers[i]; | |
if (!dictionary.containsKey(number)) { | |
dictionary.put(number, new HashSet<Integer>()); | |
} | |
HashSet<Integer> indexSet = dictionary.get(number); | |
indexSet.add(i); | |
} | |
// Print the dictionary | |
for (Map.Entry<Integer, HashSet<Integer>> entry : dictionary.entrySet()) { | |
int number = entry.getKey(); | |
HashSet<Integer> indexSet = entry.getValue(); | |
System.out.println("Number: " + number + ", Index Set: " + indexSet.toString()); | |
} | |
} | |
} | |
/* | |
Run example: | |
Number: 1, Index Set: [0] | |
Number: 2, Index Set: [1, 3] | |
Number: 3, Index Set: [2, 6] | |
Number: 4, Index Set: [4, 9] | |
Number: 5, Index Set: [5] | |
Number: 6, Index Set: [7] | |
Number: 7, Index Set: [8] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment