2

I have a function (findByNames) that accepts spreading parameter like the example below :

List<Users> findByNames(String... names)
{
  ...
} 

And as parameter i have a list :

List<String> names = asList("john","abraham");

So i would like to convert the names list to spreading object to use findByNames function, is that possible using Java 8 ? I tried this solution :

MapUtils.getMap(names.toArray(new String[names.size()]))

but it's not working !

Thank's for you' time.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
AHmedRef
  • 2,555
  • 12
  • 43
  • 75
  • Its called [Varargs](https://docs.oracle.com/javase/7/docs/technotes/guides/language/varargs.html) – Naman Feb 15 '19 at 14:48
  • Please check this link https://stackoverflow.com/questions/9863742/how-to-pass-an-arraylist-to-a-varargs-method-parameter – Hatice Feb 15 '19 at 14:55
  • @haticeSigirci no is not working, in my case !, did you tried it ? – AHmedRef Feb 15 '19 at 15:14
  • 3
    The problem seems to be that you say that you want to invoke `findByNames`, but instead of just doing it, you’re invoking `MapUtils.getMap`. – Holger Feb 15 '19 at 16:25

1 Answers1

12

Convert the List<String> into an array String[]:

// Java-8(tag in question)
List<Users> users = findByNames(names.toArray(new String[0]));
// Java-11
List<Users> users = findByNames(names.toArray(String[]::new));
Naman
  • 27,789
  • 26
  • 218
  • 353
  • in the case of Redis, it's not working for me. my command is `syncCommands.mget(redisKeys.toArray(new String[redisKeys.size()]));` and I get error msg `[Ljava.lang.String; cannot be cast to java.lang.String`. Any help? – roottraveller Nov 20 '19 at 11:56
  • @roottraveller what type is `redisKeys` in your case? If its `List`, it should just work fine. Are you sure the error is not `mget` accepting a `String` and not `String[]`? – Naman Nov 20 '19 at 12:00
  • I fixed it. I just restarted the Redis cluster and it started working. – roottraveller Nov 21 '19 at 06:11