Polyglot CheatSheet - Collection Conversions

Updated: 2021-11-19

Array to Map

Javascript

const arr = [
  { key: 'foo', val: 'bar' },
  { key: 'hello', val: 'world' },
];

const result = new Map(arr.map((i) => [i.key, i.val]));

Hack/PHP

Arrays::pull(collection, vgrip, kgrip)

or

Dict\pull_with_key(traversable, value_func, key_func)

To Tuple/List

Python

  • tuple(s): converts any kind of sequence into a tuple
  • list(s): converts any kind of sequence into a list

Set to Array

Javascript

[...set];

e.g.

const s = new Set();
s.add('a');
s.add('b');
s.add('a');
[...s][('a', 'b')];

More Java/Scala Conversions

Scala Seq to Java List

list.seqAsJavaList()

Scala Double to Java Double

java.lang.Double.valueOf(scalaDoubleValue)

or convert a seq

list.map(java.lang.Double.valueOf)

InputStream to String

Warning: This solution converts different line breaks (like \r\n) to \n.

String result = new BufferedReader(new InputStreamReader(inputStream))
  .lines().collect(Collectors.joining("\n"));

Hack

vec to Vector

new Vector($v)

vec to Map

new Map($v)

vec to Set

new Set($v)

vec to array

Arrays::fromVec($v)