logo

Polyglot CheatSheet - List / Vector / Array

Last Updated: 2022-12-20

Abstractions

C++

  • std::vector: similar to C arrays, but dynamically-resizable;
  • std::list/std::forward_list: a linked list of values; and
  • std::deque: similar to a vector in that it allows random access, but also supports constant time insertion and removal from both ends of the array.

Rust

  • std::vec::Vec or std::collections::VecDeque
  • std::collections::LinkedList

Create

C++

#include <vector>

std::vector<int> v {1, 2, 3, 4};

// or

std::vector<int> v = {1, 2, 3, 4};

Java

Create empty:

List<Integer> v = new ArrayList<>();
// Array
String[] arr = new String[]{"A", "B", "C"};

// List
List<Integer> v =
    new ArrayList<>(Arrays.asList(5, 4, 3, 2, 1));

Init Stream

Stream<Integer> intStream = Stream.of(1,2,3,4);

Copy from existing:

List<Integer> copy = new ArrayList<>(origin)

Rust

let mut l = LinkedList::new();
let v = vec![5, 4, 3, 2, 1];

Hack

Hack Array:

$v = vec[]

Hack Collection:

$v = Vector{}
$v = vec[1, 2, 3];
$v = vec($container);

PHP

array()

Python

>>> [[0] * 4] * 4
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Repeated Values In List/Tuple

List

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Tuple.

>>> (0,) * 10
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

Notice the comma in (0,), otherwise it is scalar calculation

>>> (1) * 10
10

Init 2D array

>>> a = [[0] * 3 for _ in range(4)]
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

2D 8-Directions

>>> [(x, y) for x in d for y in d if x != 0 or y != 0]
[(1, 1), (1, 0), (1, -1), (0, 1), (0, -1), (-1, 1), (-1, 0), (-1, -1)]

Ruby

>> numbers = ['zero', 'one', 'two']
=> ["zero", "one", "two"]

JavaScript

const clone = originArray.slice(0);

Get By Index

Ruby

>> numbers[1]
=> "one"

Add Elements

C++

Use push_back or emplace_back:

std::vector<int> v = {1, 2};
v.emplace_back(3);
v.push_back(4);

emplace_back will forward the args to the constructor, while push_back takes the value as the input:

std::vector<std::pair<std::string, int>> v = {std::make_pair("a", 1),
                                              std::make_pair("b", 2)};
v.emplace_back("c", 3);
v.push_back(std::make_pair("d", 4));

Java

list.add()

Python

list.append()

JavaScript

// insert, front
list.unshift();

// insert, back
list.push();

Go

var s []int
s = append(s, 1)

Hack

$v[] = 4;

Ruby

>> numbers.push('three', 'four')
=> ["zero", "one", "two", "three", "four"]

Remove Element

JavaScript

// delete from back
list.pop();

// delete from front
list.shift();

Delete without changing indices of other elements(leaving a hole)

delete array[i];

Delete and shift other elements forward(modifying array in place:

var index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

Delete by filtering

keys.filter((key) => key != 'foo');

Ruby

>> numbers.drop(2)
=> ["two", "three", "four"]

Last Item

C++

  • vector::back: returns a reference
  • vector::end: returns an iterator just past the element

Contains

C++

Use std::find

std::vector<int> v { 10, 20, 30, 40 };
int val = 20;
if (std::find(v.begin(), v.end(), val) != v.end()) {
  ...
}

Hack

Hack Array:

C\contains_key($v, 1)

or

C\contains($v, 3)

Python

Use in:

>>> a = [1, 2, 3]
>>> 1 in a
True
>>> 4 in a
False

JavaScript

Use includes:

arr.includes(element);

Map

JavaScript

[1, 2, 3].map((x) => x * 2);

Python

map(lambda x: x * 2, [1, 2, 3])

Array Length

JavaScript

[1, 2, 3].length;

Python

len([1,2,3])

Count Elements

Hack

C\count($v)

Type Signature

Hack

vec<TValue>

Type Test

Hack

is_vec($v)

Join As String

Python

join is a method of string instead of a list, since any iterable can be joined.

>>> "|".join(["a", "b", "c"])
'a|b|c'

Scala

Use mkString

scala> List("a","b","c").mkString("|")
res1: String = a|b|c

Java 8+

String joined = String.join(",", Arrays.asList("a", "b", "c"));

or

String joined = Arrays.asList("a", "b", "c").stream().collect(Collectors.joining(","));

Manipulate before joining, e.g. to Uppercase

String joined = Arrays.asList("a", "b", "c")
    .stream()
    .map(String::toUpperCase)
    .collect(Collectors.joining(","));

Another example:

List<BigDecimal> buffer = ...
String s = buffer.stream()
              .map(x -> x.toString())
              .collect(Collectors.joining(",")));

PHP

implode

Join Two Arrays

javascript

[1].concat([2])[(1, 2)];

IndexOf

var array = [2, 5, 9];
var index = array.indexOf(5);

Subarray

Scala

arr.drop(2)

Python

arr[2:]

JavaScript

arr.slice();

Convert To Other Type

Java

Array to Stream

Arrays.stream(array);

String to IntStream

IntStream is = "abc".chars();

Array to Immutable List

private static final Thing[] PRIVATE_VALUES = { ... };
public static final List<Thing> VALUES =
    Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));

Arrays.asList does not return ArrayList, so does not support addAll() or add(), will throw UnsupportedOperationException

Convert to string array

String[] y = x.toArray(new String[0]);

Primitive Array To List

Use boxed()

int[] nums = new int[]{1,2,3};
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());

Array To List

Integer[] nums = new Integer[]{1,2,3};
List<Integer> list = Arrays.stream(nums).collect(Collectors.toList());

Create ArrayList From Array

ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

Deconstruct

JavaScript

const [a, b, c] = str.split('-');

Python

>>> a, *b, c = [1, 2, 3, 4, 5, 6]
>>> a
1
>>> b
[2, 3, 4, 5]
>>> c
6

PHP

list($a, $b, $c) = Str\split(",", $str);

Max / Min

Java

Java 8+

int[] a = new int[]{1,2,3};
int min = Arrays.stream(a).min().getAsInt();

JavaScript

Math.max and Math.min do not work on arrays, for example Math.max(1,2,3,4). To get the max/min of an array, use apply

Math.max.apply(Math, [1, 2, 3, 4]);
Math.min.apply(Math, [1, 2, 3, 4]);

Flatten

Python

There's no flatten builtin, but can use list comprehension:

flat_list = [item for sublist in nestedlist for item in sublist]

which means:

for sublist in nestedlist:
    for item in sublist:
        flat_list.append(item)

zip

Python

Zip

>>> x = (1, 2, 3)
>>> y = ('a', 'b', 'c')
>>> z = list(zip(x, y))
>>> z
[(1, 'a'), (2, 'b'), (3, 'c')]

Unzip. Use * to unpack z

>>> x, y = list(zip(*z))
>>> x
(1, 2, 3)
>>> y
('a', 'b', 'c')

JavaScript

const a = [1, 2, 3]
const b = ['A', 'B', 'C']
a.map((v, i) => [v, b[i]]
// [[1, 'A'], [2, 'B'], [3, 'C']]

Comprehensions

Python

names = [c.name for c in customers if c.admin]