Incompatible types error when put ArrayList as value to a map

dinesh babu :

I am getting the list if it already exists and adding an element to it.

Code snippet:

Map<Integer, List<Integer>> map = new TreeMap<>(Collections.reverseOrder());
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
    int factor = 0;
    int num = sc.nextInt();
    for (int j = 1; j <= num; j++)
      if (num % j == 0) factor++;  //just getting factor count of each input

    map.put(factor, map.getOrDefault(factor, new ArrayList<>()).add(num)); // error line

Error details:

error: incompatible types: boolean cannot be converted to List

How to solve this trouble?

nazar_art :

Because add() has boolean as return type. You can not put boolean value to map which have List<Integer> as a value.

You need to create ArrayList -> add an element to it first.

And only then put it to a map as a value:

List<Integer> list = new ArrayList<>();
list.add(num);
map.put(factor, map.getOrDefault(factor, list));

From Java 9+, you could use List.of():

map.put(factor, map.getOrDefault(factor, List.of(num)));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=371792&siteId=1