logo

Collection Conversions

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]));

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"));

string to char array

Python

>>> s = "asdf"
>>> [c for c in s]
['a', 's', 'd', 'f']

String and Bytes

Go

myString := string(myBytes[:])

Python: str and bytes

Use .encode() and .decode()

>>> 'ABC'.encode()
b'ABC'
>>> b'ABC'.decode()
'ABC'

String to Char Array

Java

String str = "someString";
char[] charArray = str.toCharArray();

Join Array/List As String

Java

Join array:

String[] names = new String[]{"a", "b", "c"};
System.out.println(String.join(",", names));
//a,b,c

Join List:

List<String> names = Arrays.asList("a", "b", "c");
System.out.println(String.join(",", names));
//a,b,c

Manipulate list before joining:

List<String> names = Arrays.asList("a", "b", "c");
String joined = names.stream()
        .map(String::toUpperCase)
        .collect(Collectors.joining(","));
System.out.println(joined);
//A,B,C

String to List

Python

>>> '9'.split()
['9']