Programming Languages Cheat Sheet
A quick reference for data structures, basic syntax, and essential APIs in Lua, JavaScript, Go, Python, and Java.
A quick reference guide to data structures, basic syntax, and essential APIs across multiple languages.
| Feature | List | Tuple | Set | Dict | Queue | Stack |
|---|
| Syntax | [] | () | {} | {k: v} | Queue() | list |
| Mutability | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ |
| Ordered | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ |
| Duplicates | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ |
| Index access | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
| Slicing | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
# List - mutable listmy_list = [1, 2, 3] # Create a listmy_list.append(4) # Append an elementmy_list[1] = 10 # Modify the element at index 1subset = my_list[1:3] # Slice: elements from index 1 to 3 (exclusive)# Tuple - immutable tuplemy_tuple = (1, 2, 3) # Create a tupleitem = my_tuple[0] # Index access# Set - deduplicated collectionmy_set = {1, 2, 3} # Create a setmy_set.add(4) # Add an elementunion = set1 | set2 # Unionintersection = set1 & set2 # Intersection# Dict - key-value pairsmy_dict = {"a": 1, "b": 2} # Create a dictvalue = my_dict.get("c", 0) # Get a value, default to 0 if key missingmy_dict["d"] = 4 # Add or update a key-value pairkeys = my_dict.keys() # Get all keys
| Feature | Slice | Array | Map | Queue/Stack |
|---|
| Syntax | []T | [n]T | map[K]V | slice |
| Mutability | ✅ | ✅ | ✅ | ✅ |
| Ordered | ✅ | ✅ | ❌ | ✅ |
| Duplicates | ✅ | ✅ | ❌ | ✅ |
| Index access | ✅ | ✅ | ❌ | ✅ |
[]T: Slice, a dynamic array with variable length; T is the element type[n]T: Array, fixed length; n is the length, T is the element typemap[K]V: Map (hash table); K is the key type, V is the value type
// Slice - dynamic array, variable lengthslice := []int{1, 2, 3} // Create and initialize a sliceslice = append(slice, 4) // Append an elementslice[1] = 10 // Modify the element at index 1subset := slice[1:3] // Slice: elements from index 1 to 3 (exclusive)// Array - fixed-length arrayarr := [3]int{1, 2, 3} // Create an int array of length 3arr[0] = 5 // Modify an element// Map - hash table, key-value storagem := map[string]int{"a": 1, "b": 2} // Create and initialize a mapvalue, exists := m["c"] // Get value and existence flag by keym["d"] = 4 // Add or update a key-value pairdelete(m, "a") // Delete a key-value pair// Stack operations (implemented with a slice)stack := []int{} // Create an empty stackstack = append(stack, 1) // pushtop := stack[len(stack)-1] // peek: view the top elementstack = stack[:len(stack)-1] // pop// Queue operations (implemented with a slice)queue := []int{} // Create an empty queuequeue = append(queue, 1) // enqueuefront := queue[0] // peek: view the front elementqueue = queue[1:] // dequeue
| Feature | Array | Object | Set | Map | Queue | Stack |
|---|
| Syntax | [] | {} | new Set() | new Map() | array | array |
| Mutability | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Ordered | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ |
| Duplicates | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ |
| Index access | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ |
// Arrayconst arr = [1, 2, 3]; // Create an arrayarr.push(4); // Append an elementarr[1] = 10; // Modify the element at index 1const subset = arr.slice(1, 3); // Slice: elements from index 1 to 3 (exclusive)arr.forEach(x => console.log(x)); // Iterate over the arrayconst mapped = arr.map(x => x * 2); // Map: transform each elementconst filtered = arr.filter(x => x > 1); // Filter: keep matching elements// Objectconst obj = {a: 1, b: 2}; // Create an objectconst value = obj.c || 0; // Get a property, default if missingobj.d = 4; // Add or update a propertyconst keys = Object.keys(obj); // Get all keysconst values = Object.values(obj); // Get all values// Set - deduplicated collectionconst set = new Set([1, 2, 2, 3]); // Create a setset.add(4); // Add an elementset.has(1); // Check whether an element existsset.delete(1); // Delete an element// Map - key-value mappingconst map = new Map([['a', 1], ['b', 2]]); // Create a mapmap.set('c', 3); // Set a key-value pairmap.get('a'); // Get a valuemap.has('a'); // Check whether a key exists
| Feature | List | Array | Set | Map | Queue | Stack |
|---|
| Syntax | List | T[] | Set | Map | Queue | Stack |
| Mutability | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ |
| Ordered | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ |
| Duplicates | ✅ | ❌ | ❌ | ❌(key) | ✅ | ✅ |
| Index access | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
// List (ArrayList)List<Integer> list = new ArrayList<>();list.add(1);list.add(2);list.set(1, 10);List<Integer> subList = list.subList(0, 2);list.remove(Integer.valueOf(1));// Set (HashSet)Set<Integer> set = new HashSet<>();set.add(1);set.contains(1);set.remove(1);// Map (HashMap)Map<String, Integer> map = new HashMap<>();map.put("a", 1);map.getOrDefault("c", 0);map.containsKey("a");Set<String> keys = map.keySet();// Queue (LinkedList)Queue<Integer> queue = new LinkedList<>();queue.offer(1);Integer front = queue.poll();// Stack (Stack)Stack<Integer> stack = new Stack<>();stack.push(1);Integer top = stack.pop();Integer peek = stack.peek();
| Feature | Table(Array) | Table(Dict) |
|---|
| Syntax | {} | {} |
| Mutability | ✅ | ✅ |
| Ordered | ✅ | ❌ |
| Duplicates | ✅ | ❌(key) |
| Index access | ✅ | ❌ |
-- Table as Arrayarr = {1, 2, 3}table.insert(arr, 4)arr[2] = 10table.remove(arr, 1)-- Table as Dictionarydict = {a = 1, b = 2}dict["c"] = 3dict.d = 4value = dict.a or 0-- Common table operationscount = #arrfor i, v in ipairs(arr) do print(i, v)endfor k, v in pairs(dict) do print(k, v)end
# Variablesx = 10 # Integername = "Python" # Stringis_active = True # Boolean# Operators+, -, *, /, //, %, ** # Arithmetic: add, subtract, multiply, divide, floor divide, modulo, power==, !=, >, <, >=, <= # Comparison operatorsand, or, not # Logical operatorsin, is # Membership test, identity test# Functionsdef greet(name): return f"Hello, {name}"
// Variablesvar x int = 10 // Full declarationvar name string = "Go"isActive := true // Short declaration (type inferred)// Operators+, -, *, /, % // Arithmetic operators==, !=, >, <, >=, <= // Comparison operators&&, ||, ! // Logical operators// Functionsfunc greet(name string) string { // Parameter and return types return fmt.Sprintf("Hello, %s", name)}
// Variableslet x = 10; // Mutable variableconst name = "JavaScript"; // Immutable constantlet isActive = true; // Boolean// Operators+, -, *, /, % // Arithmetic operators==, ===, !=, !==, >, <, >=, <= // Comparison (== compares values, === compares type and value)&&, ||, ! // Logical operatorsin, instanceof // Membership test, type test// Functionsfunction greet(name) { return `Hello, ${name}`;}
// Variablesint x = 10; // int typeString name = "Java"; // String typeboolean isActive = true; // boolean type// Operators+, -, *, /, % // Arithmetic operators==, !=, >, <, >=, <= // Comparison operators&&, ||, ! // Logical operatorsinstanceof // Type test// Methodspublic String greet(String name) { return "Hello, " + name;}
-- VariablesglobalVar = 10 -- Global variablelocal localVar = 20 -- Local variable (recommended)local name = "Lua"local isActive = true-- Operators+, -, *, /, %, ^ -- Arithmetic operators (^ is power)==, ~=, >, <, >=, <= -- Comparison operators (~= is not-equal)and, or, not -- Logical operators-- Functionsfunction greet(name) return "Hello, " .. name -- .. is string concatenationend
# If-elif-elseif condition: passelif condition2: passelse: pass# Ternary operatorresult = "yes" if condition else "no"# Nested conditionsif outer_condition: if inner_condition: pass else: pass
// If-else if-elseif condition {} else if condition2 {} else {}// If with initializationif x := getValue(); x > 0 { fmt.Println("positive")} else { fmt.Println("non-positive")}// Switch statementswitch value {case 1: fmt.Println("one")case 2: fmt.Println("two")default: fmt.Println("other")}
// If-else if-elseif (condition) {} else if (condition2) {} else {}// Ternary operatorresult = condition ? "yes" : "no";// Switch statementswitch (value) { case 1: console.log("one"); break; case 2: console.log("two"); break; default: console.log("other");}
// If-else if-elseif (condition) {} else if (condition2) {} else {}// Ternary operatorresult = condition ? "yes" : "no";// Switch statementswitch (value) { case 1: System.out.println("one"); break; case 2: System.out.println("two"); break; default: System.out.println("other");}// Switch expressions (Java 14+)String message = switch (value) { case 1 -> "one"; case 2 -> "two"; default -> "other";};
-- If-elseif-elseif condition thenelseif condition2 thenelseend-- Nested conditionsif outer_condition then if inner_condition then else endend-- No ternary operator in Lua-- Use if-else or logical operatorsresult = condition and "yes" or "no"
# For loop with rangefor i in range(10): # 0 to 9 passfor i in range(1, 11): # 1 to 10 passfor i in range(0, 10, 2): # 0, 2, 4, 6, 8 pass# For loop over iterablefor item in items: passfor index, item in enumerate(items): pass# While loopwhile condition: pass# Loop controlfor i in range(10): if i == 5: break # Exit loop if i == 3: continue # Skip to next iteration
// Traditional for loopfor i := 0; i < 10; i++ {}// For range over slice/arrayfor index, item := range items {}// For range over mapfor key, value := range m {}// While loop (Go only has for)for condition {}// Infinite loopfor {}// Loop controlfor i := 0; i < 10; i++ { if i == 5 { break // Exit loop } if i == 3 { continue // Skip to next iteration }}
// Traditional for loopfor (let i = 0; i < 10; i++) {}// For...of loop (iterables)for (const item of items) {}// For...in loop (object properties)for (const key in obj) {}// While loopwhile (condition) {}// Do-while loopdo {} while (condition);// Loop controlfor (let i = 0; i < 10; i++) { if (i === 5) { break; // Exit loop } if (i === 3) { continue; // Skip to next iteration }}
// Traditional for loopfor (int i = 0; i < 10; i++) {}// Enhanced for loopfor (int item : items) {}// While loopwhile (condition) {}// Do-while loopdo {} while (condition);// Loop controlfor (int i = 0; i < 10; i++) { if (i == 5) { break; // Exit loop } if (i == 3) { continue; // Skip to next iteration }}// Labeled loops (for nested loops)outer: for (int i = 0; i < 3; i++) { inner: for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { break outer; // Exit outer loop } }}
-- Numeric for loopfor i = 1, 10 do -- 1 to 10endfor i = 1, 10, 2 do -- 1, 3, 5, 7, 9end-- Generic for loop (ipairs for arrays)for i, v in ipairs(arr) doend-- Generic for loop (pairs for dictionaries)for k, v in pairs(dict) doend-- While loopwhile condition doend-- Repeat until loop (like do-while)repeatuntil condition-- Loop controlfor i = 1, 10 do if i == 5 then break -- Exit loop end if i == 3 then -- No continue in Lua, use if endend
# Lambda - anonymous functionadd = lambda x, y: x + y# Classesclass Person: def __init__(self, name): # Constructor self.name = name def greet(self): # Instance method return f"Hello, {self.name}"# List Comprehensionsquared = [x**2 for x in range(10)] # Squares of 0-9
// Multiple return valuesfunc divide(a, b int) (int, error) { // Return a result and an error if b == 0 { return 0, errors.New("division by zero") // Return an error } return a / b, nil // Return the result, error is nil}// Structstype Person struct { Name string // Struct fields Age int}func (p Person) Greet() string { // Method (value receiver) return fmt.Sprintf("Hello, %s", p.Name)}// Goroutinesgo func() { // The go keyword starts a goroutine fmt.Println("goroutine")}()// Channels - communication between goroutinesch := make(chan int) // Create a channelgo func() { ch <- 1 // Send data into the channel}()value := <-ch // Receive data from the channel
// Ternary operatorresult = condition ? a : b;// Arrow Functionconst greet = (name) => `Hello, ${name}`;// Objectsconst person = { name: "John", greet() { // Object method return `Hello, ${this.name}`; }};// Array methodsitems.forEach(item => console.log(item)); // Iterate over the arrayconst mapped = items.map(x => x * 2); // Map the arrayconst filtered = items.filter(x => x > 1); // Filter the array
// Ternary operatorresult = condition ? a : b;// Classespublic class Person { private String name; public Person(String name) { // Constructor this.name = name; } public String greet() { return "Hello, " + name; }}// Lambda expressionsRunnable r = () -> System.out.println("Hello");Predicate<Integer> isEven = x -> x % 2 == 0;List<Integer> evens = list.stream() .filter(isEven) // Filter with the Stream API .collect(Collectors.toList()); // Collect into a List
local greet = function(name) -- Anonymous function return "Hello, " .. nameend-- Multiple return valuesfunction getCoordinates() return 10, 20endlocal x, y = getCoordinates() -- Receive multiple return values-- Tables as objectslocal person = { name = "John", greet = function(self) return "Hello, " .. self.name end}person:greet() -- Call the method
# Function definitiondef greet(name, age=25): return f"Hello {name}, you are {age} years old"# Positional argumentsresult = greet("Alice", 30)# Keyword argumentsresult = greet(name="Bob", age=35)# Default argumentsresult = greet("Charlie") # Uses default age=25# Variable argumentsdef func(*args, **kwargs): print(args) # Tuple of positional args print(kwargs) # Dict of keyword argsfunc(1, 2, 3, name="Alice", age=25)
// Function definitionfunc greet(name string, age int) string { return fmt.Sprintf("Hello %s, you are %d years old", name, age)}// Named return valuesfunc calculate(a, b int) (sum, diff int) { sum = a + b diff = a - b return // Returns named variables}// Variadic functionfunc sum(numbers ...int) int { total := 0 for _, num := range numbers { total += num } return total}result := greet("Alice", 30)total := sum(1, 2, 3, 4, 5)
// Function declarationfunction greet(name, age = 25) { return `Hello ${name}, you are ${age} years old`;}// Arrow functionconst greetArrow = (name, age = 25) => `Hello ${name}, you are ${age} years old`;// Rest parametersfunction func(...args) { console.log(args); // Array of arguments}// Destructuring parametersconst greetPerson = ({name, age}) => `Hello ${name}, age ${age}`;result = greet("Alice", 30);func(1, 2, 3, "hello");
// Method definitionpublic String greet(String name, int age) { return String.format("Hello %s, you are %d years old", name, age);}// Method overloadingpublic String greet(String name) { return greet(name, 25); // Calls other method with default age}// Varargs methodpublic int sum(int... numbers) { int total = 0; for (int num : numbers) { total += num; } return total;}String result = greet("Alice", 30);int total = sum(1, 2, 3, 4, 5);
-- Function definitionfunction greet(name, age) age = age or 25 -- Default value return "Hello " .. name .. ", you are " .. age .. " years old"end-- Multiple return valuesfunction getPerson() return "Alice", 30end-- Variable argumentsfunction sum(...) local total = 0 for i, v in ipairs({...}) do total = total + v end return totalendresult = greet("Alice", 30)name, age = getPerson() -- Multiple assignmenttotal = sum(1, 2, 3, 4, 5)
| Type | Passing Mechanism | Behavior |
|---|
| Immutable (int, str, tuple) | Pass by object reference | Cannot modify original |
| Mutable (list, dict, set) | Pass by object reference | Can modify original content |
| Objects | Pass by object reference | Can modify object attributes |
# Immutable types - cannot modify originaldef modify_int(x): x = 10 # Only modifies local copy return xnum = 5result = modify_int(num) # num is still 5# Mutable types - can modify originaldef modify_list(lst): lst.append(4) # Modifies original list return lstmy_list = [1, 2, 3]modify_list(my_list) # my_list is now [1, 2, 3, 4]# To avoid modifying mutable typesdef safe_modify(lst): new_lst = lst.copy() # Create copy new_lst.append(4) return new_lst
| Type | Passing Mechanism | Behavior |
|---|
| All types | Pass by value | Copies value to function |
| Pointers | Pass by reference | Can modify original via pointer |
| Slices/Maps/Channels | Pass by value (reference types) | Copy header, can modify underlying data |
// Value types - pass by copyfunc modifyInt(x int) { x = 10 // Only modifies local copy}num := 5modifyInt(num) // num is still 5// Pointer types - pass by referencefunc modifyIntPtr(x *int) { *x = 10 // Modifies original value}num := 5modifyIntPtr(&num) // num is now 10// Reference types (slice, map, channel)func modifySlice(s []int) { s[0] = 10 // Modifies underlying array s = append(s, 4) // Only modifies local slice header}slice := []int{1, 2, 3}modifySlice(slice) // slice[0] is now 10, but length unchanged
| Type | Passing Mechanism | Behavior |
|---|
| Primitives (number, string, boolean) | Pass by value | Copies value to function |
| Objects (including arrays, functions) | Pass by reference | Can modify original object |
// Primitive types - pass by valuefunction modifyNum(x) { x = 10; // Only modifies local copy return x;}let num = 5;modifyNum(num); // num is still 5// Object types - pass by referencefunction modifyArray(arr) { arr.push(4); // Modifies original array return arr;}let myArray = [1, 2, 3];modifyArray(myArray); // myArray is now [1, 2, 3, 4]// To avoid modifying objectsfunction safeModifyArray(arr) { const newArr = [...arr]; // Create copy newArr.push(4); return newArr;}
| Type | Passing Mechanism | Behavior |
|---|
| Primitives (int, double, boolean, etc.) | Pass by value | Copies value to method |
| Objects (including arrays) | Pass by value (reference) | Copies reference, can modify object |
// Primitive types - pass by valuepublic void modifyInt(int x) { x = 10; // Only modifies local copy}int num = 5;modifyInt(num); // num is still 5// Object types - pass by reference valuepublic void modifyArray(List<Integer> list) { list.add(4); // Modifies original list list = new ArrayList<>(); // Only modifies local reference}List<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3));modifyArray(myList); // myList is now [1, 2, 3, 4]// To avoid modifying objectspublic void safeModifyArray(List<Integer> list) { List<Integer> newList = new ArrayList<>(list); // Create copy newList.add(4);}
| Type | Passing Mechanism | Behavior |
|---|
| All types | Pass by reference | Tables passed by reference, others by value |
-- Numbers/strings - pass by valuefunction modifyNum(x) x = 10 -- Only modifies local copy return xendlocal num = 5modifyNum(num) -- num is still 5-- Tables - pass by referencefunction modifyTable(tbl) tbl.value = 10 -- Modifies original table return tblendlocal myTable = {value = 5}modifyTable(myTable) -- myTable.value is now 10-- To avoid modifying tablesfunction safeModifyTable(tbl) local newTbl = {} for k, v in pairs(tbl) do newTbl[k] = v end newTbl.value = 10 return newTblend
# Higher-order functiondef apply_operation(func, numbers): return [func(x) for x in numbers]# Lambda functionssquare = lambda x: x ** 2result = apply_operation(square, [1, 2, 3, 4])# Closuresdef make_multiplier(factor): def multiplier(x): return x * factor # Captures factor from outer scope return multipliertimes_three = make_multiplier(3)result = times_three(5) # Returns 15# Decorators (higher-order functions)def timer(func): import time def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) print(f"Function took {time.time() - start} seconds") return result return wrapper@timerdef slow_function(): time.sleep(1) return "Done"
// Higher-order functionfunc applyOperation(func func(int) int, numbers []int) []int { result := make([]int, len(numbers)) for i, num := range numbers { result[i] = func(num) } return result}// Function literals (closures)func main() { square := func(x int) int { return x * x } result := applyOperation(square, []int{1, 2, 3, 4}) // Closure capturing outer variable factor := 3 multiplier := func(x int) int { return x * factor } result2 := applyOperation(multiplier, []int{1, 2, 3, 4})}
// Higher-order functionfunction applyOperation(func, numbers) { return numbers.map(func);}// Arrow functionsconst square = x => x ** 2;const result = applyOperation(square, [1, 2, 3, 4]);// Closuresfunction makeMultiplier(factor) { return function(x) { return x * factor; // Captures factor from outer scope };}const timesThree = makeMultiplier(3);const result2 = timesThree(5); // Returns 15// Function methods (bind, call, apply)const person = {name: "Alice"};function greet(greeting) { return `${greeting}, ${this.name}`;}const boundGreet = greet.bind(person);boundGreet("Hello"); // "Hello, Alice"
// Functional interfaces (Java 8+)import java.util.function.*;import java.util.stream.Collectors;// Higher-order function using streamsList<Integer> applyOperation(Function<Integer, Integer> func, List<Integer> numbers) { return numbers.stream() .map(func) .collect(Collectors.toList());}// Lambda expressionsFunction<Integer, Integer> square = x -> x * x;List<Integer> result = applyOperation(square, Arrays.asList(1, 2, 3, 4));// Closures (effectively final variables)public Function<Integer, Integer> makeMultiplier(int factor) { return x -> x * factor; // Captures factor (must be effectively final)}Function<Integer, Integer> timesThree = makeMultiplier(3);int result2 = timesThree.apply(5); // Returns 15// Method referencesList<String> names = Arrays.asList("Alice", "Bob", "Charlie");List<Integer> nameLengths = names.stream() .map(String::length) // Method reference .collect(Collectors.toList());
-- Higher-order functionfunction applyOperation(func, numbers) local result = {} for i, num in ipairs(numbers) do result[i] = func(num) end return resultend-- Anonymous functionslocal square = function(x) return x * x endlocal result = applyOperation(square, {1, 2, 3, 4})-- Closuresfunction makeMultiplier(factor) return function(x) return x * factor -- Captures factor from outer scope endendlocal timesThree = makeMultiplier(3)local result2 = timesThree(5) -- Returns 15-- Functions as first-class citizenslocal functions = { add = function(a, b) return a + b end, multiply = function(a, b) return a * b end}local sum = functions.add(5, 3)
s = "hello"s.upper() # To uppercases.lower() # To lowercases.strip() # Trim leading/trailing whitespaces.split(',') # Split the strings.startswith('prefix') # Check prefixs.endswith('suffix') # Check suffixs.replace('old', 'new') # Replace a substring
s := "hello"strings.ToUpper(s) // To uppercasestrings.ToLower(s) // To lowercasestrings.TrimSpace(s) // Trim leading/trailing whitespacestrings.Split(s, ",") // Split the stringstrings.HasPrefix(s, "prefix") // Check prefixstrings.HasSuffix(s, "suffix") // Check suffixstrings.Replace(s, "old", "new", -1) // Replace a substring
const s = "hello";s.toUpperCase(); // To uppercases.toLowerCase(); // To lowercases.trim(); // Trim leading/trailing whitespaces.split(','); // Split the strings.startsWith('prefix'); // Check prefixs.endsWith('suffix'); // Check suffixs.replace('old', 'new'); // Replace a substring
String s = "hello";s.toUpperCase(); // To uppercases.toLowerCase(); // To lowercases.trim(); // Trim leading/trailing whitespaces.split(","); // Split the strings.startsWith("prefix"); // Check prefixs.endsWith("suffix"); // Check suffixs.replace("old", "new"); // Replace a substring
s = "hello"string.upper(s) -- To uppercasestring.lower(s) -- To lowercasestring.gsub(s, "pattern", "replacement") -- Replace a patternstring.find(s, "pattern") -- Find a patternstring.sub(s, 1, 3) -- Extract a substringstring.format("%s %d", "hello", 42) -- Format a string
with open('file.txt', 'r') as f: content = f.read() # Read a filewith open('file.txt', 'w') as f: f.write('content') # Write to a filefrom pathlib import Pathpath = Path('file.txt')path.exists() # Check the pathpath.read_text() # Read file content
content, err := os.ReadFile("file.txt") // Read a fileos.WriteFile("file.txt", []byte("content"), 0644) // Write to a fileos.Stat("file.txt") // Get file infoos.ReadDir(".") // List directory contentsos.Mkdir("dir", 0755) // Create a directory
fetch('file.txt') .then(res => res.text()) // Read a file// Writing files requires the File APIconst file = new File(["content"], "file.txt");
Files.readString(Path.of("file.txt")); // Read a fileFiles.writeString(Path.of("file.txt"), "content"); // Write to a fileFiles.exists(Path.of("file.txt")); // Check whether the file exists
local file = io.open("file.txt", "r") -- Open a file for readinglocal content = file:read("*a") -- Read all contentfile:close()local file = io.open("file.txt", "w") -- Open a file for writingfile:write("content") -- Write contentfile:close()os.remove("file.txt") -- Delete a file
import jsonjson.dumps(obj) # Object to JSON stringjson.loads(json_str) # JSON string to object
json.Marshal(obj) // Object to JSON bytesjson.Unmarshal(data, &obj) // JSON bytes to object
JSON.stringify(obj); // Object to JSON stringJSON.parse(jsonStr); // JSON string to object
// JacksonObjectMapper mapper = new ObjectMapper();String json = mapper.writeValueAsString(obj); // Object to JSONMyClass obj = mapper.readValue(json, MyClass.class); // JSON to object
import requestsresponse = requests.get('https://api.example.com')data = response.json() # Parse the JSON response
resp, err := http.Get("https://api.example.com")defer resp.Body.Close()body, _ := ioutil.ReadAll(resp.Body)
fetch('https://api.example.com') .then(res => res.json()) .then(data => console.log(data));
HttpClient client = HttpClient.newHttpClient();HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com")) .build();HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
from datetime import datetimenow = datetime.now()formatted = now.strftime('%Y-%m-%d') # Format the date
now := time.Now()formatted := now.Format("2006-01-02") // Format the date (Go's reference layout)
const now = new Date();const formatted = now.toISOString(); // Convert to an ISO string
LocalDateTime now = LocalDateTime.now();String formatted = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
os.time() -- Get the current timestampos.date() -- Format the date
import randomrandom.randint(1, 10) # Random integer in [1, 10]random.choice(['a', 'b', 'c']) # Random choice
rand.Intn(10) // Random integer in [0, 10)rand.Intn(len(arr)) // Random index
Math.random(); // Random number in [0, 1)Math.floor(Math.random() * 10); // Random integer in [0, 10)Math.max(1, 2, 3); // Maximum
math.random(1, 10) -- Random integer in [1, 10]math.floor(3.14) -- Round downmath.ceil(3.14) -- Round upmath.max(1, 2, 3) -- Maximum
arr = [1, 2, 3]arr.append(4) # Append to the endarr.remove(1) # Remove an element1 in arr # Check whether an element existsarr.index(2) # Find the index of an element[x for x in arr if x > 1] # List comprehension
// Slicearr := []int{1, 2, 3}arr = append(arr, 4) // Append to the end// Mapm := make(map[string]int)m["key"] = 1 // Add a key-value pairval, ok := m["key"] // Get a value
arr = [1, 2, 3]arr.push(4); // Append to the endarr.pop(); // Remove the last elementarr.shift(); // Remove the first elementarr.includes(2); // Check whether an element existsarr.indexOf(2); // Find the index of an elementarr.filter(x => x > 1); // Filter the arrayarr.map(x => x * 2); // Map the arrayarr.reduce((acc, x) => acc + x, 0); // Reduce
// ArrayListList<Integer> list = new ArrayList<>();list.add(1); // Add an elementlist.remove(Integer.valueOf(1)); // Remove an element (by value)list.contains(1); // Check whether an element existslist.get(0); // Get an element// HashMapMap<String, Integer> map = new HashMap<>();map.put("key", 1); // Add a key-value pairmap.get("key"); // Get a valuemap.containsKey("key"); // Check whether a key exists
-- Tablearr = {1, 2, 3}table.insert(arr, 1, value) -- Insert a value at index 1table.remove(arr, 1) -- Remove the element at index 1table.sort(arr) -- Sorttable.concat(arr, ",") -- Join into a stringtable.unpack(arr) -- Unpack
import asyncioasync def fetch_data(): async with aiohttp.ClientSession() as session: async with session.get('url') as response: return await response.json()asyncio.run(fetch_data())
ch := make(chan int)go func() { ch <- 1 // Send data into the channel}()select { // Multiplexingcase v := <-ch: fmt.Println(v) // Receive datacase <-time.After(time.Second): fmt.Println("timeout") // Timeout}
// PromisePromise.resolve(1).then(x => console.log(x));// Async/Awaitasync function fetchData() { const res = await fetch('url'); const data = await res.json(); return data;}// setTimeoutsetTimeout(() => console.log('delayed'), 1000);