Common Coding Tasks Cheat Sheet: Python vs JavaScript vs Java
Side-by-side one-liners for the everyday tasks developers search for mid-task — converting types, strings, lists, dictionaries, files, dates, randomness and environment variables — each linked to a full guide with the gotchas.
By Software Side Hustles Editorial Team · Published · Updated · 5 min read
How to use this page: find the task, copy the one-liner for your language, and follow the link when the input is messy — that is where the full guides cover the edge cases that turn a one-liner into a bug. Every snippet here was run before publication.
Converting types
| Task | Python | JavaScript | Java |
|---|---|---|---|
| Int → string | str(n) | String(n) | String.valueOf(n) |
| String → int | int(s) | Number(s) / parseInt(s, 10) | Integer.parseInt(s) |
| String → float | float(s) | Number(s) | Double.parseDouble(s) |
| Round to 2 dp (display) | f"{x:.2f}" | x.toFixed(2) | String.format("%.2f", x) |
| Object → JSON | json.dumps(obj) | JSON.stringify(obj) | mapper.writeValueAsString(obj) |
| JSON → object | json.loads(s) | JSON.parse(s) | mapper.readValue(s, T.class) |
Full guides: int ↔ string in nine languages · rounding and why 0.1 + 0.2 ≠ 0.3 · parsing JSON safely.
Strings
| Task | Python | JavaScript | Java |
|---|---|---|---|
| Length | len(s) | s.length | s.length() |
| Upper / lower case | s.upper() / s.lower() | s.toUpperCase() / s.toLowerCase() | s.toUpperCase() / s.toLowerCase(Locale.ROOT) |
| Trim whitespace | s.strip() | s.trim() | s.strip() |
| Contains | "x" in s | s.includes("x") | s.contains("x") |
| Starts with | s.startswith("x") | s.startsWith("x") | s.startsWith("x") |
| Replace all | s.replace("a", "b") | s.replaceAll("a", "b") | s.replace("a", "b") |
| Split | s.split(",") | s.split(",") | s.split(",") (regex!) |
| Join | ",".join(items) | items.join(",") | String.join(",", items) |
| Reverse | s[::-1] | [...s].reverse().join("") | new StringBuilder(s).reverse().toString() |
| Format | f"{name} is {age}" | `${name} is ${age}` | "%s is %d".formatted(name, age) |
Note that JavaScript's s.replace("a", "b") replaces only the first match; use replaceAll or a regex with the g flag. Java's replace replaces every occurrence, and replaceAll takes a regex.
Full guides: substring checks · splitting and joining · reversing, including emoji.
Lists and arrays
| Task | Python | JavaScript | Java |
|---|---|---|---|
| Sort numbers | sorted(xs) | xs.toSorted((a, b) => a - b) | xs.stream().sorted().toList() |
| Sort by field | sorted(xs, key=lambda x: x["age"]) | xs.toSorted((a, b) => a.age - b.age) | xs.sort(Comparator.comparing(P::age)) |
| Remove duplicates (keep order) | list(dict.fromkeys(xs)) | [...new Set(xs)] | new ArrayList<>(new LinkedHashSet<>(xs)) |
| Filter | [x for x in xs if x > 0] | xs.filter((x) => x > 0) | xs.stream().filter(x -> x > 0).toList() |
| Map | [x * 2 for x in xs] | xs.map((x) => x * 2) | xs.stream().map(x -> x * 2).toList() |
| Sum | sum(xs) | xs.reduce((a, b) => a + b, 0) | xs.stream().mapToInt(Integer::intValue).sum() |
| Flatten one level | [x for sub in xs for x in sub] | xs.flat() | xs.stream().flatMap(List::stream).toList() |
| Last element | xs[-1] | xs.at(-1) | xs.get(xs.size() - 1) (or getLast() on Java 21+) |
| Contains | x in xs | xs.includes(x) | xs.contains(x) |
Remember: JavaScript's sort() without a comparator sorts numbers as strings, so [10, 9, 1].sort() gives [1, 10, 9].
Full guides: sorting by a property · removing duplicates · flattening nested lists · removing items while iterating.
Dictionaries, objects and maps
| Task | Python | JavaScript | Java |
|---|---|---|---|
| Key exists | k in d | Object.hasOwn(o, k) / m.has(k) | m.containsKey(k) |
| Get with default | d.get(k, 0) | o[k] ?? 0 | m.getOrDefault(k, 0) |
| Merge (right wins) | a | b | { ...a, ...b } | var m = new HashMap<>(a); m.putAll(b); |
| Iterate pairs | for k, v in d.items(): | for (const [k, v] of Object.entries(o)) | for (var e : m.entrySet()) |
| Count occurrences | Counter(xs) | xs.reduce((m, x) => m.set(x, (m.get(x) ?? 0) + 1), new Map()) | xs.stream().collect(groupingBy(x -> x, counting())) |
| Deep copy | copy.deepcopy(d) | structuredClone(o) | copy constructor / serialisation |
Full guides: checking for keys · merging · deep vs shallow copies.
Files, dates and the environment
| Task | Python | JavaScript (Node.js) | Java |
|---|---|---|---|
| Read whole file | Path("f").read_text(encoding="utf-8") | fs.readFileSync("f", "utf8") | Files.readString(Path.of("f")) |
| Read line by line | for line in open("f", encoding="utf-8"): | readline + for await | Files.lines(Path.of("f")) |
| Current UTC time | datetime.now(timezone.utc) | new Date().toISOString() | Instant.now() |
| Unix timestamp | time.time() (seconds) | Date.now() (milliseconds) | Instant.now().getEpochSecond() |
| Environment variable | os.environ.get("KEY") | process.env.KEY | System.getenv("KEY") |
| Sleep 1 second | time.sleep(1) | await new Promise((r) => setTimeout(r, 1000)) | Thread.sleep(1000) |
| Working directory | os.getcwd() | process.cwd() | System.getProperty("user.dir") |
Full guides: reading files · dates and time zones.
Randomness and IDs
| Task | Python | JavaScript | Java |
|---|---|---|---|
| Random int 1–6 inclusive | random.randint(1, 6) | Math.floor(Math.random() * 6) + 1 | ThreadLocalRandom.current().nextInt(1, 7) |
| Random choice | random.choice(xs) | xs[Math.floor(Math.random() * xs.length)] | xs.get(ThreadLocalRandom.current().nextInt(xs.size())) |
| Shuffle | random.shuffle(xs) (in place) | Fisher–Yates loop | Collections.shuffle(xs) |
| UUID | uuid.uuid4() | crypto.randomUUID() | UUID.randomUUID() |
| Secure token | secrets.token_urlsafe(32) | crypto.getRandomValues(new Uint8Array(32)) | SecureRandom |
Watch the bounds: Python's randint includes both ends; Java's nextInt(1, 7) excludes the upper bound. Never use random / Math.random() for passwords, reset tokens or session IDs — use the cryptographic APIs in the last row. Also avoid xs.sort(() => Math.random() - 0.5) for shuffling: it is biased.
Version control
| Task | Command |
|---|---|
| Undo last commit, keep changes | git reset --soft HEAD~1 |
| Undo a pushed commit | git revert HEAD |
| Fix last commit message | git commit --amend -m "..." |
| Abort a conflicted merge | git merge --abort |
| Find the commit that broke something | git bisect start, git bisect bad, git bisect good <sha> |
Full guides: undoing commits · resolving merge conflicts.
Frequently asked questions
Why do these one-liners differ between languages?
Each language has its own conventions about mutation (does sort change the list?), inclusive versus exclusive ranges, and how strict parsing is. Those differences are the source of many bugs when switching languages.
Which one-liners are most likely to cause bugs?
String-to-number parsing, default sorting in JavaScript, Java's regex-based split, floating-point rounding and anything involving time zones. Each has a dedicated guide linked above.
Are these snippets safe for production?
They are correct for well-formed input. Production code should also handle invalid input, which the linked guides cover.
Where this skill pays off
Knowing the idiomatic way to do something in several languages — and where each one bites — is exactly what makes developers effective reviewers of AI-generated code across languages. If that sounds like you, see how software engineers earn money training AI models or explore side hustles for software engineers.