1

This question is in continuation with my previous question

So, I want create a list with suppose 5 a characters, 10 b, 20 c and 10 d.

for(char chr = 'a'; chr <= 'c'; chr++){
    alphabetList.addAll(Collections.nCopies(5, chr));
}

With above code I can add 5 copies of each char. My question is how can we add 5 a characters, 10 b, 20 c and 10 d. How can we do this. Any functional way?

Community
  • 1
  • 1
Alex
  • 19
  • 8
  • 1
    Share your code, your tries, how the count of each is store, you see there is a lot of details missing, please give them and think about the other details you miss to give – azro Apr 11 '20 at 08:43
  • And do you know whether it' 5, 10 or 20 ? – azro Apr 11 '20 at 08:49
  • yes. this count is fine for now. – Alex Apr 11 '20 at 08:54
  • First store the characters with their count in the `Map`. then by looping over the map, you can add in the list like below. `Map characterMap = new HashMap<>();` `List alphabetList = new ArrayList<>();` `characterMap.forEach((key, value) -> alphabetList.addAll(Collections.nCopies(value, key)));` – Hadi J Apr 11 '20 at 09:08
  • I asked you "How" and you tell me "yes" ? – azro Apr 11 '20 at 09:11

3 Answers3

2

You could create a LinkedHashMap (to retain order) of the characters and counts and then iterate over it and call nCopies:

Map<Character, Integer> numCopies = new LinkedHashMap<>();
numCopies.put('a', 5);
numCopies.put('b', 10);
numCopies.put('c', 20);
numCopies.put('d', 10);

for (Map.Entry<Character, Integer> e : numCopies) {
    alphabetList.addAll(Collections.nCopies(e.getVale(), e.getKey());
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • `numCopies.forEach((key, value) ->alphabetList.addAll(Collections.nCopies(value, key)));` is more consice. – Hadi J Apr 11 '20 at 09:14
1

Just use an array to store how often want to repeat each character:

int[] charCount={5,10,20,10};

for(char chr = 'a',int i=0; chr <= 'd'&&i<charCount.length; chr++,i++){
    alphabetList.addAll(Collections.nCopies(charCount[i], chr));
}

I have also added a counter variable i that indicates the position in the array.

Then, you can just use the array at that index to get how ofter you want to repeat the character.

In order to prevent ArrayIndexOutOfNoundsExceptions (if the array is too small), I have added a check that the loop aborts in that case.

dan1st
  • 12,568
  • 8
  • 34
  • 67
1

You can define a map and fill it with known values, namely chars and the number of it repetitions.

Map<Character, Integer> map = new HashMap<>();

{
  map.put('a', 5);
  map.put('b', 10);
  map.put('c', 20);
  map.put('d', 10);
}

And then use it like this

for(char chr = 'a'; chr <= 'c'; chr++){
    alphabetList.addAll(Collections.nCopies(map.get(chr), chr));
}
donquih0te
  • 597
  • 3
  • 22