Collections & Containers
- C
- C++
- C#
- Java
- Rust
- Go
- Javascript
- Typescript
- Python
// Arrays (Fixed Size)
#include <stdint.h> // Since C99
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
// Arrays must be initialized with a concrete size.
int32_t integer_array_name[20];
// You can skip the size declaration if you initialize the array on the same line.
int32_t integer_array_name[] = {0, 1, 2, 3, 4};
char char_array[] = {'a', 'b', 'c'};
// In C, strings are an array of characters
// This is a string with lenght = 20. In C you have to account for the '\0' character.
char variable_name[21];
char variable_name[] = "Some string";
// More about this on the String Section
// Const Declaration
const int32_t integer_array_name[] = {0, 1, 2, 3, 4};
// ------------------------------------
// Direct Access
// ------------------------------------
my_array[0] = something;
// ------------------------------------
// Push & Pop
// ------------------------------------
// Not Available
// ------------------------------------
// Size / Length
// ------------------------------------
// Not Available
// You must have another variable to keep track of the current size.
// You usually would encapsulate all this logic in a specific header/C file.
// ------------------------------------
// Count (How many of)
// ------------------------------------
// Not Available
// ------------------------------------
// Filter
// ------------------------------------
// Not Available
// You need to create your own logic
// ------------------------------------
// Find (return Index)
// ------------------------------------
// Not Available
// You need to create your own logic
// You usually would encapsulate all this logic in a specific header/C file.
int find(int element, int size, int my_array[]) // Just an example
{
for(int i = 0; i < size; i++)
{
if (element == my_array[i]) // String comparison is diferent in C. Check string section.
{
return i;
}
}
return -1; // Not found
}
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
// Not Available
// You need to create your own logic
// ------------------------------------
// Sort
// ------------------------------------
// Not Available
// You need to create your own logic
// ------------------------------------
// Comparing
// ------------------------------------
// Not Available
// You need to create your own logic
bool is_equal(int size, int first_array[], int second_array[])
{
for(int i = 0; i < size; i++)
{
if (first_array[i] != second_array[i])
{
return false;
}
}
return true;
}
// ------------------------------------
// Copy / Clone
// ------------------------------------
// Not Available
// You need to create your own logic
// ------------------------------------
// Slice
// ------------------------------------
// Not Available
// You need to create your own logic
// ------------------------------------
// Printing Members
// ------------------------------------
// You usually would encapsulate all this logic in a specific header/C file.
void print_members(int size, int my_array[]) // Just an example
{
for(int i = 0; i < size; i++)
{
printf("%d ", my_array[i]);
}
}
// ------------------------------------
// Multi Dimensional Array
// ------------------------------------
int32_t multi_dimensional_array[20][30];
// Dynamic Size Arrays
// No Native Support.
// Use malloc(), realloc(), and free(), or wrap this logic in a struct.
typedef struct IntArray
{
int *items;
int size;
int capacity;
} IntArray;
void push(IntArray *array, int value)
{
if (array->size == array->capacity)
{
array->capacity = array->capacity == 0 ? 4 : array->capacity * 2;
array->items = realloc(array->items, array->capacity * sizeof(int));
}
array->items[array->size] = value;
array->size++;
}
// No Native List
// You can code your own or use a 3rd lib
// No Native Vectors
// You can code your own or use a 3rd lib
// No Native Tuples
// You can code your own or use a 3rd lib
// No Native Stack
// You can code your own or use a 3rd lib
// No Native Queue
// You can code your own or use a 3rd lib
// No Native Dictionary
// You can code your own or use a 3rd lib
// Arrays
// std::array will clean up after itself when it goes out of scope,
// so there's no need to do any kind of manual cleanup.
#include <array> // Since (C++11)
#include <cstdint> // std::int32_t Type (Since C++11)
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
// Fixed Type and Size
std::array<std::int32_t, 5> myArray;
// Uniform Initialization (since C++11)
std::array<std::int32_t, 5> myArray { 9, 7, 5, 3, 1 };
// It is allowed to omit the type and size.
// They can only be omitted together, but not one or the other,
// and only if the array is explicitly initialized. (Since C++17)
std::array myArray { 9, 7, 5, 3, 1 };
// Const Declaration
const std::array<std::int32_t, 5> myArray { 9, 7, 5, 3, 1 };
std::array<std::int32_t, 5> const myArray { 9, 7, 5, 3, 1 };
// ------------------------------------
// Direct Access
// ------------------------------------
myArray[0] = 14; // No bounds-checking
myArray.at(0) = 14; // with bounds-checking
// ------------------------------------
// Push & Pop
// ------------------------------------
// Not Available
// ------------------------------------
// Size / Length
// ------------------------------------
std::int32_t mySize = myArray.size();
std::int32_t myMaxSize = myArray.max_size();
// ------------------------------------
// Count (How many of)
// ------------------------------------
#include <algorithm> // For std::count, std::count_if
// Ex. 1
std::int32_t const target = 2;
std::int32_t howMany = std::count(std::begin(my_collection), std::end(my_collection), target); // Prefer. Works on C-style arrays too
std::int32_t howMany = std::count(my_collection.begin(), my_collection.end(), target);
// Ex. 2
std::int32_t howManyOdd = std::count_if(std::begin(my_collection), std::end(my_collection), /* Lambda Function */);
std::int32_t howManyOdd = std::count_if(std::begin(my_collection), std::end(my_collection), [](auto element) { return element % 2 != 0; } );
// Check Lambda Section for more about Lambda.
// Check Type Inference Section for more about "auto"
// ------------------------------------
// Filter
// ------------------------------------
std::vector<std::int32_t> filtered;
std::copy_if(std::begin(myArray), std::end(myArray), std::back_inserter(filtered), [](auto element) { return element > 10; });
// ------------------------------------
// Find (return Index)
// ------------------------------------
auto iterator = std::find(std::begin(myArray), std::end(myArray), target);
auto index = iterator == std::end(myArray) ? -1 : std::distance(std::begin(myArray), iterator);
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
std::int32_t total = std::accumulate(std::begin(my_collection), std::end(my_collection), 0); // 0 (zero) is the starting value
// ------------------------------------
// Sort
// ------------------------------------
#include <algorithm> // For std::sort, std::partial_sort
// Ex. 1
std::sort(std::begin(my_collection), std::end(my_collection));
// Ex. 2
std::sort(std::begin(my_collection), std::end(my_collection), /* Lambda Function for custom sort */ );
std::sort(std::begin(my_collection), std::end(my_collection), [](auto firstElement, auto secondElement) { return abs(firstElement) > abs(secondElement); } );
// Ex. 3
// You can use "std::partial_sort()" for more performance if you
// dont need to show everything sorted at the same time. (Like a pagination)
std::partial_sort(std::begin(my_collection), /* Last element to be sorted */ ,end(my_collection));
std::partial_sort(std::begin(my_collection), ( std::begin(my_collection) + 10 ) ,end(my_collection)); // First 10 will be sorted
// ------------------------------------
// Comparing
// ------------------------------------
#include <algorithm> // For std::equal
bool isEqual = std::equal(std::begin(my_collection), std::end(my_collection), std::begin(my_other_collection), std::end(my_other_collection));
// ------------------------------------
// Copy / Clone
// ------------------------------------
#include <algorithm> // For std::copy
// Example 1
// C++ operator "=" actually creates a real copy
auto myCopyArray = myArray; // Check Type Inference Section for more about "auto"
// Example 2
std::array<std::int32_t, 5> myCopyArray;
// Example 3
std::copy(std::begin(myArray), std::end(myArray), std::begin(myCopyArray));
// ------------------------------------
// Slice
// ------------------------------------
std::vector<std::int32_t> slice(std::begin(myArray) + 1, std::begin(myArray) + 3);
// ------------------------------------
// Printing Members
// ------------------------------------
// For-each (Ranged For) (Since C++ 11)
// element will be a copy of the current array element
for (auto element : myArray) { std::cout << element << " "; }
// The ampersand makes element a reference to the actual array element,
// preventing a copy from being made
for (auto &element : myArray) { std::cout << element << " "; }
// element is a const reference to the currently iterated array element
for (const auto &element : myArray) { std::cout << element << " "; }
for (auto const &element : myArray) { std::cout << element << " "; }
// In for-each loops element declarations, for performance reasons,
// if your elements are non-fundamental types, use references or const references
// else (your elements are basic types) use the copy element syntax
// ------------------------------------
// As a function Parameter
// ------------------------------------
void my_function(const std::array<std::int32_t, 5> &myArray)
{
// non-mutable code
}
void my_function(std::array<std::int32_t, 5> const &myArray)
{
// non-mutable code
}
// ------------------------------------
// Multi Dimensional Array
// ------------------------------------
std::array<std::array<std::int32_t, 3>, 3> my_multi_array;
std::array<std::array<std::int32_t, 3>, 3> my_multi_array {{{1,2,3},{4,5,6},{7,8,9}}};
// Legacy (Avoid)
int integer_array_name[5];
int integer_array_name[] = {0, 1, 2, 3, 4};
int multi_dimensional_array[3][3];
// List
// std::list will clean up after itself when it goes out of scope,
// so there’s no need to do any kind of manual cleanup.
#include <list>
#include <cstdint> // std::int32_t Type (Since C++11)
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
// Fixed Type but NOT size/length
std::list<std::int32_t> myList;
// Uniform Initialization (since C++11)
std::list<std::int32_t> myList { 9, 7, 5, 3, 1 };
// Const Declaration
const std::list<std::int32_t> myList { 9, 7, 5, 3, 1 };
std::list<std::int32_t> const myList { 9, 7, 5, 3, 1 };
// ------------------------------------
// Direct Access
// ------------------------------------
// Not Available
// ------------------------------------
// Push & Pop
// ------------------------------------
myList.push_front(30); // Add at the beginning
myList.push_back(30); // Add at the end
myList.pop_front(); // Removes the first element of the list, and reduces size of the list by 1.
myList.pop_back(); // Removes the last element of the list, and reduces size of the list by 1.
// ------------------------------------
// Size / Length
// ------------------------------------
myList.size();
myList.max_size();
// ------------------------------------
// Count (How many of)
// ------------------------------------
auto howMany = std::count(myList.begin(), myList.end(), target);
auto howManyOdd = std::count_if(myList.begin(), myList.end(), [](auto element) { return element % 2 != 0; });
// ------------------------------------
// Filter
// ------------------------------------
std::list<std::int32_t> filtered;
std::copy_if(myList.begin(), myList.end(), std::back_inserter(filtered), [](auto element) { return element > 10; });
// ------------------------------------
// Find (return Index)
// ------------------------------------
auto iterator = std::find(myList.begin(), myList.end(), target);
auto index = iterator == myList.end() ? -1 : std::distance(myList.begin(), iterator);
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
auto total = std::accumulate(myList.begin(), myList.end(), 0);
// ------------------------------------
// Sort
// ------------------------------------
myList.sort();
myList.sort([](auto firstElement, auto secondElement) { return firstElement > secondElement; });
// ------------------------------------
// Comparing
// ------------------------------------
bool isEqual = myList == myOtherList;
// ------------------------------------
// Copy / Clone
// ------------------------------------
auto myCopyList = myList;
// ------------------------------------
// Slice
// ------------------------------------
std::list<std::int32_t> slice;
auto first = std::next(myList.begin(), 1);
auto last = std::next(myList.begin(), 3);
std::copy(first, last, std::back_inserter(slice));
// ------------------------------------
// Printing Members
// ------------------------------------
// For-each (Ranged For) (Since C++ 11)
// element will be a copy of the current array element
for (auto element : myArray) { std::cout << element << " "; }
// The ampersand makes element a reference to the actual array element,
// preventing a copy from being made
for (auto &element : myArray) { std::cout << element << " "; }
// element is a const reference to the currently iterated array element
for (const auto &element : myArray) { std::cout << element << " "; }
for (auto const &element : myArray) { std::cout << element << " "; }
// In for-each loops element declarations, for performance reasons,
// if your elements are non-fundamental types, use references or const references
// else (your elements are basic types) use the copy element syntax
// ------------------------------------
// As a function Parameter
// ------------------------------------
void my_function(const std::list<std::int32_t> &myList)
{
// non-mutable code
}
void my_function(std::list<std::int32_t> const &myList)
{
// non-mutable code
}
// Vectors
// std::vector will clean up after itself when it goes out of scope,
// so there’s no need to do any kind of manual cleanup.
#include <vector> // Since C++03
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
// Fixed Type but NOT size/length
std::vector<std::int32_t> myVector;
// Uniform Initialization (since C++11)
std::vector<std::int32_t> myVector { 9, 7, 5, 3, 1 };
// Const Declaration
const std::vector<std::int32_t> myVector { 9, 7, 5, 3, 1 };
std::vector<std::int32_t> const myVector { 9, 7, 5, 3, 1 };
// ------------------------------------
// Direct Access
// ------------------------------------
myVector[0] = 14; // No bounds-checking
myVector.at(0) = 14; // with bounds-checking
// ------------------------------------
// Push & Pop
// ------------------------------------
myVector.insert(myVector.begin(), 30); // Add at the beginning
myVector.push_back(30); // Add at the end
myVector.erase(myVector.begin()); // Removes the first element of the vector, and reduces size of the vector by 1.
myVector.pop_back(); // Removes the last element of the vector, and reduces size of the vector by 1.
// ------------------------------------
// Size / Length
// ------------------------------------
myVector.size();
myVector.max_size();
// ------------------------------------
// Count (How many of)
// ------------------------------------
auto howMany = std::count(myVector.begin(), myVector.end(), target);
auto howManyOdd = std::count_if(myVector.begin(), myVector.end(), [](auto element) { return element % 2 != 0; });
// ------------------------------------
// Filter
// ------------------------------------
std::vector<std::int32_t> filtered;
std::copy_if(myVector.begin(), myVector.end(), std::back_inserter(filtered), [](auto element) { return element > 10; });
// ------------------------------------
// Find (return Index)
// ------------------------------------
auto iterator = std::find(myVector.begin(), myVector.end(), target);
auto index = iterator == myVector.end() ? -1 : std::distance(myVector.begin(), iterator);
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
auto total = std::accumulate(myVector.begin(), myVector.end(), 0);
// ------------------------------------
// Sort
// ------------------------------------
std::sort(myVector.begin(), myVector.end());
std::sort(myVector.begin(), myVector.end(), [](auto firstElement, auto secondElement) { return firstElement > secondElement; });
// ------------------------------------
// Comparing
// ------------------------------------
bool isEqual = myVector == myOtherVector;
// ------------------------------------
// Copy / Clone
// ------------------------------------
auto myCopyVector = myVector;
// ------------------------------------
// Slice
// ------------------------------------
std::vector<std::int32_t> slice(myVector.begin() + 1, myVector.begin() + 3);
// ------------------------------------
// Printing Members
// ------------------------------------
// For-each (Ranged For) (Since C++ 11)
// element will be a copy of the current array element
for (auto element : myArray) { std::cout << element << " "; }
// The ampersand makes element a reference to the actual array element,
// preventing a copy from being made
for (auto &element : myArray) { std::cout << element << " "; }
// element is a const reference to the currently iterated array element
for (const auto &element : myArray) { std::cout << element << " "; }
for (auto const &element : myArray) { std::cout << element << " "; }
// In for-each loops element declarations, for performance reasons,
// if your elements are non-fundamental types, use references or const references
// else (your elements are basic types) use the copy element syntax
// ------------------------------------
// As a function Parameter
// ------------------------------------
void my_function(const std::vector<std::int32_t> &myVector)
{
// non-mutable code
}
void my_function(std::vector<std::int32_t> const &myVector)
{
// non-mutable code
}
// ------------------------------------
// Multi Dimensional Vector
// ------------------------------------
std::vector<std::vector<std::int32_t> > my_multi_vector;
std::vector<std::vector<std::int32_t> > my_multi_vector {{{1,2,3},{4,5,6},{7,8,9}}};
// Alternative modern syntax
std::vector<std::vector<std::int32_t>> my_multi_vector;
std::vector<std::vector<std::int32_t>> my_multi_vector {{1,2,3},{4,5,6},{7,8,9}};
// Tuples
#include <tuple>
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
// Uniform Initialization (since C++11)
std::tuple<std::string, std::int32_t, bool> myTuple { "hello", 10, true };
// Const Declaration
const std::tuple<std::string, std::int32_t, bool> myTuple { "hello", 10, true };
std::tuple<std::string, std::int32_t, bool> const myTuple { "hello", 10, true };
// ------------------------------------
// Direct Access
// ------------------------------------
auto text = std::get<0>(myTuple);
auto number = std::get<1>(myTuple);
// ------------------------------------
// Push & Pop
// ------------------------------------
// Not Available
// Tuples have fixed size and fixed element positions.
// ------------------------------------
// Size / Length
// ------------------------------------
auto tupleSize = std::tuple_size<decltype(myTuple)>::value;
// ------------------------------------
// Count (How many of)
// ------------------------------------
// ------------------------------------
// Filter
// ------------------------------------
// Not Available
// Tuples are fixed heterogeneous values, not runtime-filterable collections.
// ------------------------------------
// Find (return Index)
// ------------------------------------
// Not Available
// Access tuple members by known compile-time index or structured binding.
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
// Not Available for general heterogeneous tuples.
// Use std::apply with custom logic when the tuple values are compatible.
// ------------------------------------
// Sort
// ------------------------------------
// Not Available
// Tuples represent fixed positions, not sortable collections.
// ------------------------------------
// Comparing
// ------------------------------------
bool isEqual = myTuple == myOtherTuple;
// ------------------------------------
// Copy / Clone
// ------------------------------------
auto myCopyTuple = myTuple;
// ------------------------------------
// Slice
// ------------------------------------
// Not Available
// Use a new tuple with the wanted fields.
auto slice = std::make_tuple(std::get<0>(myTuple), std::get<1>(myTuple));
// ------------------------------------
// Printing Members
// ------------------------------------
std::cout << std::get<0>(myTuple) << " " << std::get<1>(myTuple) << " " << std::get<2>(myTuple);
// ------------------------------------
// As a function Parameter
// ------------------------------------
void my_function(const std::tuple<std::string, std::int32_t, bool> &myTuple)
{
// non-mutable code
}
More Info:
- https://www.learncpp.com/cpp-tutorial/variable-assignment-and-initialization/
- https://www.learncpp.com/cpp-tutorial/6-15-an-introduction-to-stdarray/
- https://www.learncpp.com/cpp-tutorial/6-16-an-introduction-to-stdvector/
- https://www.geeksforgeeks.org/list-cpp-stl/
- https://en.cppreference.com/w/cpp/container/list
- https://en.cppreference.com/w/cpp/algorithm
// Array
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
int[] myArray = new int[5];
int[] myArray = { 1, 2, 3 };
var myArray = new[] { 1, 2, 3 };
// Const Declaration
// Arrays are mutable. Use readonly fields or immutable collections when needed.
readonly int[] myArray = { 1, 2, 3 };
// ------------------------------------
// Direct Access
// ------------------------------------
myArray[0] = 14;
int value = myArray[0];
// ------------------------------------
// Push & Pop
// ------------------------------------
// Not Available for fixed-size arrays.
// Use List<T> for dynamic collections.
// ------------------------------------
// Size / Length
// ------------------------------------
int length = myArray.Length;
// ------------------------------------
// Count (How many of)
// ------------------------------------
int howMany = myArray.Count(element => element == target);
// ------------------------------------
// Filter
// ------------------------------------
int[] filtered = myArray.Where(element => element > 10).ToArray();
// ------------------------------------
// Find (return Index)
// ------------------------------------
int index = Array.IndexOf(myArray, target);
int index = Array.FindIndex(myArray, element => element > 10);
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
int total = myArray.Sum();
int total = myArray.Aggregate(0, (result, element) => result + element);
// ------------------------------------
// Sort
// ------------------------------------
Array.Sort(myArray);
Array.Sort(myArray, (first, second) => second.CompareTo(first));
// ------------------------------------
// Comparing
// ------------------------------------
bool isEqual = myArray.SequenceEqual(otherArray);
// ------------------------------------
// Copy / Clone
// ------------------------------------
int[] copy = myArray.ToArray();
int[] copy = (int[])myArray.Clone();
// ------------------------------------
// Slice
// ------------------------------------
int[] slice = myArray[1..3]; // Since C# 8.0
// ------------------------------------
// Printing Members
// ------------------------------------
Console.WriteLine(string.Join(", ", myArray));
foreach (int element in myArray)
{
Console.WriteLine(element);
}
// ------------------------------------
// As a function Parameter
// ------------------------------------
void MyFunction(int[] values)
{
// ...
}
// List
List<int> myList = new List<int>();
List<int> myList = new() { 1, 2, 3 };
myList[0] = 14;
myList.Add(10);
myList.Insert(0, 10);
myList.RemoveAt(0);
myList.Remove(10);
int length = myList.Count;
int howMany = myList.Count(element => element == target);
List<int> filtered = myList.Where(element => element > 10).ToList();
int index = myList.FindIndex(element => element > 10);
int total = myList.Sum();
myList.Sort();
myList.Sort((first, second) => second.CompareTo(first));
bool isEqual = myList.SequenceEqual(otherList);
List<int> copy = new List<int>(myList);
List<int> slice = myList.GetRange(1, 2);
Console.WriteLine(string.Join(", ", myList));
void MyFunction(List<int> values)
{
// ...
}
// Dictionary
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
Dictionary<string, int> myDictionary = new()
{
["first"] = 1,
["second"] = 2,
};
myDictionary["third"] = 3;
int value = myDictionary["first"];
bool hasKey = myDictionary.ContainsKey("first");
bool found = myDictionary.TryGetValue("first", out int value);
myDictionary.Remove("first");
int length = myDictionary.Count;
foreach (KeyValuePair<string, int> item in myDictionary)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
// Array
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
int[] myArray = new int[5];
int[] myArray = { 1, 2, 3 };
// Const Declaration
// final prevents reassignment, but the array contents are still mutable.
final int[] MY_ARRAY = { 1, 2, 3 };
// ------------------------------------
// Direct Access
// ------------------------------------
myArray[0] = 14;
int value = myArray[0];
// ------------------------------------
// Push & Pop
// ------------------------------------
// Not Available for fixed-size arrays.
// Use ArrayList<T> for dynamic collections.
// ------------------------------------
// Size / Length
// ------------------------------------
int length = myArray.length;
// ------------------------------------
// Count (How many of)
// ------------------------------------
long howMany = Arrays.stream(myArray).filter(element -> element == target).count();
// ------------------------------------
// Filter
// ------------------------------------
int[] filtered = Arrays.stream(myArray).filter(element -> element > 10).toArray();
// ------------------------------------
// Find (return Index)
// ------------------------------------
int index = -1;
for (int i = 0; i < myArray.length; i++) {
if (myArray[i] == target) {
index = i;
break;
}
}
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
int total = Arrays.stream(myArray).sum();
// ------------------------------------
// Sort
// ------------------------------------
Arrays.sort(myArray);
// ------------------------------------
// Comparing
// ------------------------------------
boolean isEqual = Arrays.equals(myArray, otherArray);
// ------------------------------------
// Copy / Clone
// ------------------------------------
int[] copy = Arrays.copyOf(myArray, myArray.length);
int[] copy = myArray.clone();
// ------------------------------------
// Slice
// ------------------------------------
int[] slice = Arrays.copyOfRange(myArray, 1, 3);
// ------------------------------------
// Printing Members
// ------------------------------------
System.out.println(Arrays.toString(myArray));
for (int element : myArray) {
System.out.println(element);
}
// ------------------------------------
// As a function Parameter
// ------------------------------------
void myFunction(int[] values) {
// ...
}
// ArrayList
ArrayList<Integer> myList = new ArrayList<>();
ArrayList<Integer> myList = new ArrayList<>(List.of(1, 2, 3));
myList.set(0, 14);
int value = myList.get(0);
myList.add(10);
myList.add(0, 10);
myList.remove(0);
myList.remove(Integer.valueOf(10));
int length = myList.size();
long howMany = myList.stream().filter(element -> element == target).count();
List<Integer> filtered = myList.stream().filter(element -> element > 10).toList(); // Since Java 16
int index = myList.indexOf(target);
int total = myList.stream().mapToInt(Integer::intValue).sum();
Collections.sort(myList);
myList.sort(Comparator.reverseOrder());
boolean isEqual = myList.equals(otherList);
ArrayList<Integer> copy = new ArrayList<>(myList);
List<Integer> slice = myList.subList(1, 3);
System.out.println(myList);
void myFunction(List<Integer> values) {
// ...
}
// HashMap
HashMap<String, Integer> myMap = new HashMap<>();
myMap.put("first", 1);
myMap.put("second", 2);
int value = myMap.get("first");
boolean hasKey = myMap.containsKey("first");
myMap.remove("first");
int length = myMap.size();
for (Map.Entry<String, Integer> item : myMap.entrySet()) {
System.out.println(item.getKey() + ": " + item.getValue());
}
// Array
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
let my_array: [i32; 3] = [1, 2, 3];
let my_array = [0; 5];
// Const Declaration
const MY_ARRAY: [i32; 3] = [1, 2, 3];
// ------------------------------------
// Direct Access
// ------------------------------------
let value = my_array[0];
let value = my_array.get(0);
// ------------------------------------
// Push & Pop
// ------------------------------------
// Not Available for fixed-size arrays.
// Use Vec<T> for dynamic collections.
// ------------------------------------
// Size / Length
// ------------------------------------
let length = my_array.len();
// ------------------------------------
// Count (How many of)
// ------------------------------------
let how_many = my_array.iter().filter(|&&element| element == target).count();
// ------------------------------------
// Filter
// ------------------------------------
let filtered: Vec<i32> = my_array.iter().copied().filter(|element| *element > 10).collect();
// ------------------------------------
// Find (return Index)
// ------------------------------------
let index = my_array.iter().position(|element| *element == target);
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
let total: i32 = my_array.iter().sum();
// ------------------------------------
// Sort
// ------------------------------------
let mut values = my_array;
values.sort();
// ------------------------------------
// Comparing
// ------------------------------------
let is_equal = my_array == other_array;
// ------------------------------------
// Copy / Clone
// ------------------------------------
let copy = my_array;
let copy = my_array.clone();
// ------------------------------------
// Slice
// ------------------------------------
let slice = &my_array[1..3];
// ------------------------------------
// Printing Members
// ------------------------------------
println!("{:?}", my_array);
for element in my_array {
println!("{}", element);
}
// ------------------------------------
// As a function Parameter
// ------------------------------------
fn my_function(values: &[i32]) {
// ...
}
// Vec
let mut my_vector: Vec<i32> = Vec::new();
let mut my_vector = vec![1, 2, 3];
my_vector[0] = 14;
let value = my_vector[0];
let value = my_vector.get(0);
my_vector.push(10);
let last = my_vector.pop();
my_vector.insert(0, 10);
my_vector.remove(0);
let length = my_vector.len();
let how_many = my_vector.iter().filter(|&&element| element == target).count();
let filtered: Vec<i32> = my_vector.iter().copied().filter(|element| *element > 10).collect();
let index = my_vector.iter().position(|element| *element == target);
let total: i32 = my_vector.iter().sum();
my_vector.sort();
my_vector.sort_by(|first, second| second.cmp(first));
let is_equal = my_vector == other_vector;
let copy = my_vector.clone();
let slice = &my_vector[1..3];
println!("{:?}", my_vector);
fn my_function(values: &[i32]) {
// ...
}
// Tuple
let my_tuple = ("hello", 10, true);
let text = my_tuple.0;
let number = my_tuple.1;
// Tuples have fixed size and fixed types.
// Push, pop, filter, and sort are Not Available.
fn my_function(value: (&str, i32, bool)) {
// ...
}
// HashMap
use std::collections::HashMap;
let mut my_map = HashMap::new();
my_map.insert("first", 1);
my_map.insert("second", 2);
let value = my_map.get("first");
let has_key = my_map.contains_key("first");
my_map.remove("first");
let length = my_map.len();
for (key, value) in &my_map {
println!("{}: {}", key, value);
}
// Array
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
var myArray [3]int
myArray := [3]int{1, 2, 3}
myArray := [...]int{1, 2, 3}
// Const Declaration
// Not Available for arrays. const only works with primitive constant values.
// ------------------------------------
// Direct Access
// ------------------------------------
myArray[0] = 14
value := myArray[0]
// ------------------------------------
// Push & Pop
// ------------------------------------
// Not Available for fixed-size arrays.
// Use slices for dynamic collections.
// ------------------------------------
// Size / Length
// ------------------------------------
length := len(myArray)
// ------------------------------------
// Count (How many of)
// ------------------------------------
howMany := 0
for _, element := range myArray {
if element == target {
howMany++
}
}
// ------------------------------------
// Filter
// ------------------------------------
filtered := []int{}
for _, element := range myArray {
if element > 10 {
filtered = append(filtered, element)
}
}
// ------------------------------------
// Find (return Index)
// ------------------------------------
index := -1
for i, element := range myArray {
if element == target {
index = i
break
}
}
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
total := 0
for _, element := range myArray {
total += element
}
// ------------------------------------
// Sort
// ------------------------------------
sort.Ints(myArray[:])
// ------------------------------------
// Comparing
// ------------------------------------
isEqual := myArray == otherArray
// ------------------------------------
// Copy / Clone
// ------------------------------------
copyArray := myArray
// ------------------------------------
// Slice
// ------------------------------------
slice := myArray[1:3]
// ------------------------------------
// Printing Members
// ------------------------------------
fmt.Println(myArray)
for _, element := range myArray {
fmt.Println(element)
}
// ------------------------------------
// As a function Parameter
// ------------------------------------
func myFunction(values [3]int) {
// ...
}
// Slice
mySlice := []int{}
mySlice := []int{1, 2, 3}
mySlice := make([]int, 0, 10)
mySlice[0] = 14
value := mySlice[0]
mySlice = append(mySlice, 10)
last := mySlice[len(mySlice)-1]
mySlice = mySlice[:len(mySlice)-1]
length := len(mySlice)
capacity := cap(mySlice)
howMany := 0
for _, element := range mySlice {
if element == target {
howMany++
}
}
filtered := []int{}
for _, element := range mySlice {
if element > 10 {
filtered = append(filtered, element)
}
}
index := -1
for i, element := range mySlice {
if element == target {
index = i
break
}
}
total := 0
for _, element := range mySlice {
total += element
}
sort.Ints(mySlice)
isEqual := slices.Equal(mySlice, otherSlice) // Since Go 1.21
copySlice := make([]int, len(mySlice))
copy(copySlice, mySlice)
slice := mySlice[1:3]
fmt.Println(mySlice)
func myFunction(values []int) {
// ...
}
// Map
myMap := map[string]int{}
myMap := map[string]int{
"first": 1,
"second": 2,
}
myMap["third"] = 3
value := myMap["first"]
value, ok := myMap["first"]
delete(myMap, "first")
length := len(myMap)
for key, value := range myMap {
fmt.Println(key, value)
}
// Array / Lists / Vector
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
var myArray = []; // avoid var
let myArray = [];
let myArray = [1, 2, 3];
let myArray = new Array(3); // Size
// An array can store elements of any type.
let myArray = [1, "hi", function(){}, { key: 'value' }];
// Const Declaration
// Const here means that you cant change the type (from array to something else)
// You can still change its members
const myArray = [1, 2, 3];
// ------------------------------------
// Direct Access
// ------------------------------------
myArray[0] = 14;
let value = myArray[0];
// ------------------------------------
// Push & Pop
// ------------------------------------
myArray.push(10); // Add at the end
myArray.unshift(10); // Add at the beginning
myArray.pop(); // Removes and Returns the element at the end
myArray.shift(); // Removes and Returns the element at the beginning
// ------------------------------------
// Size / Length
// ------------------------------------
let length = myArray.length;
// ------------------------------------
// Filter
// ------------------------------------
let filtered = myArray.filter(element => element > 10);
// ------------------------------------
// Count (How many of)
// ------------------------------------
let howMany = myArray.filter(element => element === target).length;
// ------------------------------------
// Find
// ------------------------------------
myArray.indexOf(element);
myArray.lastIndexOf(element);
myArray.findIndex(element => element > 10);
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
let total = myArray.reduce((result, element) => result + element, 0);
// ------------------------------------
// Sort
// ------------------------------------
myArray.sort(); // Sorts as strings by default
myArray.sort((first, second) => first - second);
myArray.sort((first, second) => second - first);
// ------------------------------------
// Comparing
// ------------------------------------
let isEqual = myArray.length === otherArray.length
&& myArray.every((element, index) => element === otherArray[index]);
// ------------------------------------
// Copy / Clone
// ------------------------------------
// Real Copy - Using Spread Operator (Since ES6)
const myRealCopy = [...myArray];
// Old Way
const myRealCopy = myArray.slice();
const myRealCopy = myArray.splice(0); // Real copy, but mutates the original array
const myRealCopy = myArray.concat();
// WONT WORK
const myFakeCopy = myArray;
// Arrays are reference types in JavaScript!!!
// Thats like creating a pointer (Be careful) It WONT create a copy
// ------------------------------------
// Slice
// ------------------------------------
let slice = myArray.slice(1, 3);
// ------------------------------------
// Printing Members
// ------------------------------------
// You can just output the array
console.log(myArray);
// or
for (const element of myArray) {
console.log(`${element} `);
}
// ------------------------------------
// As a function Parameter
// ------------------------------------
function myFunction(values) {
// ...
}
// No Native Tuple
// But you can workaround with arrays. See More Info bellow
const myTuple = ["hello", 10];
const first = myTuple[0];
const second = myTuple[1];
// No Native Stack
// But you can workaround with arrays.
const stack = [];
stack.push(10);
const value = stack.pop();
// No Native Queue
// But you can workaround with arrays.
const queue = [];
queue.push(10);
const value = queue.shift();
// Dictionary
const myObject = {};
myObject["first"] = 1;
myObject.second = 2;
const value = myObject["first"];
delete myObject["first"];
const myMap = new Map();
myMap.set("first", 1);
myMap.set("second", 2);
const value = myMap.get("first");
const hasKey = myMap.has("first");
myMap.delete("first");
const length = myMap.size;
More Info:
// Array / Lists
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
let variableName: number[] = [];
let variableName: number[] = [1, 2, 3];
let variableName: Array<number> = [1, 2, 3];
// Const Declaration
const variableName: number[] = [1, 2, 3];
const variableName: Array<number> = [1, 2, 3];
// ------------------------------------
// Direct Access
// ------------------------------------
variableName[0] = 14;
let value: number = variableName[0];
// ------------------------------------
// Push & Pop
// ------------------------------------
variableName.push(10);
variableName.unshift(10);
let last = variableName.pop();
let first = variableName.shift();
// ------------------------------------
// Size / Length
// ------------------------------------
let length: number = variableName.length;
// ------------------------------------
// Count (How many of)
// ------------------------------------
let howMany: number = variableName.filter(element => element === target).length;
// ------------------------------------
// Filter
// ------------------------------------
let filtered: number[] = variableName.filter(element => element > 10);
// ------------------------------------
// Find (return Index)
// ------------------------------------
let index: number = variableName.indexOf(target);
let index: number = variableName.findIndex(element => element > 10);
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
let total: number = variableName.reduce((result, element) => result + element, 0);
// ------------------------------------
// Sort
// ------------------------------------
variableName.sort((first, second) => first - second);
variableName.sort((first, second) => second - first);
// ------------------------------------
// Comparing
// ------------------------------------
let isEqual: boolean = variableName.length === otherArray.length
&& variableName.every((element, index) => element === otherArray[index]);
// ------------------------------------
// Copy / Clone
// ------------------------------------
let copy: number[] = [...variableName];
let copy: number[] = variableName.slice();
// ------------------------------------
// Slice
// ------------------------------------
let slice: number[] = variableName.slice(1, 3);
// ------------------------------------
// Printing Members
// ------------------------------------
console.log(variableName);
for (const element of variableName) {
console.log(element);
}
// ------------------------------------
// As a function Parameter
// ------------------------------------
function myFunction(values: number[]): void {
// ...
}
// Tuple
// ------------------------------------
// Declaration & Initialization
// ------------------------------------
let myTuple: [string, number];
myTuple = ["hello", 10];
// Const Declaration
const myTuple: readonly [string, number] = ["hello", 10];
// ------------------------------------
// Direct Access
// ------------------------------------
let text: string = myTuple[0];
let numberValue: number = myTuple[1];
// ------------------------------------
// Push & Pop
// ------------------------------------
// Avoid mutating tuples.
// Use readonly tuples when you want fixed shape.
// ------------------------------------
// Size / Length
// ------------------------------------
let length: number = myTuple.length;
// ------------------------------------
// Count (How many of)
// ------------------------------------
let howMany: number = myTuple.filter(element => element === target).length;
// ------------------------------------
// Filter
// ------------------------------------
let filtered = myTuple.filter(element => element !== undefined);
// ------------------------------------
// Find (return Index)
// ------------------------------------
let index: number = myTuple.findIndex(element => element === target);
// ------------------------------------
// Accumulate (sum all values)
// ------------------------------------
// Usually Not Available for mixed-type tuples.
// Use arrays for repeated values of one type.
// ------------------------------------
// Sort
// ------------------------------------
// Usually Not Available.
// Tuples represent fixed positions, not sortable collections.
// ------------------------------------
// Comparing
// ------------------------------------
let isEqual: boolean = myTuple.length === otherTuple.length
&& myTuple.every((element, index) => element === otherTuple[index]);
// ------------------------------------
// Copy / Clone
// ------------------------------------
let copy = [...myTuple] as [string, number];
// ------------------------------------
// Slice
// ------------------------------------
let slice = myTuple.slice(0, 1);
// ------------------------------------
// Printing Members
// ------------------------------------
console.log(myTuple);
// ------------------------------------
// As a function Parameter
// ------------------------------------
function myFunction(value: [string, number]): void {
// ...
}
More Info:
# Array / List / Vector / Stack
# ------------------------------------
# Declaration & Initialization
# ------------------------------------
my_list = []
my_list = [1, 2, 3]
my_list = [1, "Hello", 3.4] # list with mixed datatypes
my_list = ["mouse", [8, 4, 6], ['a']] # nested list
# Type Hint List
from typing import List # For collections, the name of the type is capitalized (List)
my_list: List[int] = [1, 2, 3]
my_list: list[int] = [1, 2, 3] # Since Python 3.9
# Const Declaration
MY_CONSTANT = [1, 2, 3] # Just a convention. Still Mutable
# ------------------------------------
# Direct Access
# ------------------------------------
my_list[0] = 14
my_list[-1] = 14 # Last Element
my_list[-2] = 14 # Second last and so on
# ------------------------------------
# Push & Pop
# ------------------------------------
my_list.append(element) # Add to the end of the list
my_list.insert(index, element) # Add the element at specified index location
my_list.pop() # Remove the last element of the list
my_list.pop(index) # Removes the element at the specified index
# ------------------------------------
# Size / Length
# ------------------------------------
len(my_list)
# ------------------------------------
# Count (How many of)
# ------------------------------------
how_many = my_list.count(target)
how_many = sum(1 for element in my_list if element == target)
# ------------------------------------
# Filter
# ------------------------------------
filtered = [element for element in my_list if element > 10]
filtered = list(filter(lambda element: element > 10, my_list))
# ------------------------------------
# Find (return Index)
# ------------------------------------
index = my_list.index(element) # Returns the index of the FIRST element with the specified value
# ------------------------------------
# Accumulate (sum all values)
# ------------------------------------
total = sum(my_list)
# ------------------------------------
# Sort
# ------------------------------------
my_list.sort()
my_list.sort(reverse=True)
sorted_list = sorted(my_list)
# ------------------------------------
# Comparing
# ------------------------------------
is_equal = my_list == other_list
# ------------------------------------
# Copy / Clone
# ------------------------------------
# Real Copy - Using copy() method
my_real_copy = my_list.copy()
# Real Copy - Using list() constructor
my_real_copy = list(my_list)
# Real Copy - Using slice
my_real_copy = my_list[:]
# WONT WORK
my_fake_copy = my_list
# Arrays are reference types in Python!!!
# Thats like creating a pointer (Be careful) It WONT create a copy
# ------------------------------------
# Slice
# ------------------------------------
slice = my_list[1:3]
slice = my_list[:3]
slice = my_list[1:]
# ------------------------------------
# Printing Members
# ------------------------------------
print(my_list)
for element in my_list:
print(f"{element} ")
# ------------------------------------
# As a function Parameter
# ------------------------------------
def my_function(values: list[int]) -> None:
# ...
# Tuples
# ------------------------------------
# Declaration & Initialization
# ------------------------------------
my_tuple = (1, 2, 3)
# In Python tuples are written with round brackets.
# A tuple is a collection which is ordered and unchangeable.
from typing import Tuple
# For tuples of fixed size, we specify the types of all the elements
x: Tuple[int, str, float] = (3, "yes", 7.5)
# For tuples of variable size, we use one type and ellipsis
x: Tuple[int, ...] = (1, 2, 3)
# Const Declaration
MY_CONSTANT = (1, 2, 3)
# ------------------------------------
# Direct Access
# ------------------------------------
value = my_tuple[0]
value = my_tuple[-1]
# ------------------------------------
# Push & Pop
# ------------------------------------
# Not Available.
# Tuples are immutable.
# ------------------------------------
# Size / Length
# ------------------------------------
length = len(my_tuple)
# ------------------------------------
# Count (How many of)
# ------------------------------------
how_many = my_tuple.count(target)
# ------------------------------------
# Filter
# ------------------------------------
filtered = tuple(element for element in my_tuple if element > 10)
# ------------------------------------
# Find (return Index)
# ------------------------------------
index = my_tuple.index(target)
# ------------------------------------
# Accumulate (sum all values)
# ------------------------------------
total = sum(my_tuple)
# ------------------------------------
# Sort
# ------------------------------------
sorted_tuple = tuple(sorted(my_tuple))
# ------------------------------------
# Comparing
# ------------------------------------
is_equal = my_tuple == other_tuple
# ------------------------------------
# Copy / Clone
# ------------------------------------
copy = tuple(my_tuple)
# ------------------------------------
# Slice
# ------------------------------------
slice = my_tuple[1:3]
# ------------------------------------
# Printing Members
# ------------------------------------
print(my_tuple)
for element in my_tuple:
print(element)
# ------------------------------------
# As a function Parameter
# ------------------------------------
def my_function(value: tuple[int, int, int]) -> None:
# ...
# Queue
from collections import deque
queue = deque()
queue.append(10)
queue.append(20)
value = queue.popleft()
length = len(queue)
# Dictionary
my_dictionary = {}
my_dictionary = {"first": 1, "second": 2}
my_dictionary["third"] = 3
value = my_dictionary["first"]
value = my_dictionary.get("first")
has_key = "first" in my_dictionary
del my_dictionary["first"]
length = len(my_dictionary)
for key, value in my_dictionary.items():
print(f"{key}: {value}")
More Info: