Reputation: 381
Is there any way to create a loop which will be creating new List
static Map<Integer, List> dataMap = new HashMap<>();
public static void dec_hex() {
// Map<Integer, Integer> dataMap = new HashMap<>();
// dataMap.put(0, 0);
List<Integer> ls2 = new ArrayList<Integer>();
List<Integer> ls3 = new ArrayList<Integer>();
List<Integer> ls4 = new ArrayList<Integer>();
List<Integer> ls5 = new ArrayList<Integer>();
List<Integer> ls6 = new ArrayList<Integer>();
List<Integer> ls7 = new ArrayList<Integer>();
List<Integer> ls8 = new ArrayList<Integer>();
List<Integer> ls9 = new ArrayList<Integer>();
List<Integer> ls10 = new ArrayList<Integer>();
System.out.println("Liczby");
for (int i = 0; i < 201; i++) {
String hex = Integer.toHexString(i);
System.out.println("DEC: " + i + " HEX: " + hex);
//for (int a = 2; a<11 ; a++){
if (i % 2 == 0) {
ls2.add(i);
//myList.add(i);
dataMap.put(2, ls2);
}
if (i % 3 == 0) {
ls3.add(i);
//myList.add(i);
dataMap.put(3, ls3);
}
if (i % 4 == 0) {
ls4.add(i);
//myList.add(i);
dataMap.put(4, ls4);
}
if (i % 5 == 0) {
ls5.add(i);
//myList.add(i);
dataMap.put(5, ls5);
}
if (i % 6 == 0) {
ls6.add(i);
//myList.add(i);
dataMap.put(6, ls6);
}
if (i % 7 == 0) {
ls7.add(i);
//myList.add(i);
dataMap.put(7, ls7);
}
if (i % 8 == 0) {
ls8.add(i);
// myList.add(i);
dataMap.put(8, ls8);
}
if (i % 9 == 0) {
ls9.add(i);
//myList.add(i);
dataMap.put(9, ls9);
}
if (i % 10 == 0) {
ls10.add(i);
//myList.add(i);
dataMap.put(10, ls10);
}
}
//String list = myList.toString();
//System.out.println(list);
dataMap.toString();
System.out.println(dataMap);
}
Is there any way to create a loop to check if number is divisible? If I'm going to use this
for (int a = 2; a<11 ; a++){
lsa.add(i); // lets say we've got one list
dataMap.put(a, ls);
}
The program won't work correctly cause the numbers will reapeat, cause I'm using the same lsa array.
Upvotes: 0
Views: 109
Reputation: 5423
you can shorten your by checking if the map contains a key, if not create a new list and add your data :
for (int i = 1; i < 201; i++) {
for(int j=2;j<11;j++){
if(i%j==0){
if(dataMap.containsKey(j){
dataMap.get(j).add(i);
}else{
List<Integer> list = new ArrayList<Integer>();
list.add(i);
dataMap.put(j,list);
}
}
}
}
Upvotes: 0
Reputation: 883
You can create a List of Lists.
int max = 10;
List<List<String>> listOfLists = new ArrayList<>();
for(int i=0; i<max; i++) {
//create a new list and add it to listOfLists
List<String> myList = new ArrayList<>();
listOfLists.add(myList);
}
Hope this helps. :)
Upvotes: 4
Reputation: 691805
Yes, of course. That's what a Map is for: you give it a key, and it gives you back the value.
Map<Integer, List<Integer>> dataMap = new HashMap<>();
for (int i = 0; i < 10; i++) {
dataMap.put(i, new ArrayList<>());
}
for (int i = 0; i < 201; i++) {
int key = i % 10;
List<Integer> list = dataMap.get(key);
list.add(i);
}
But since your keys are integers from 0 to 9, you could also just use a List<List<Integer>>
, instead of the map.
Upvotes: 1