SoftwareSideHustles
How-To

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

TaskPythonJavaScriptJava
Int → stringstr(n)String(n)String.valueOf(n)
String → intint(s)Number(s) / parseInt(s, 10)Integer.parseInt(s)
String → floatfloat(s)Number(s)Double.parseDouble(s)
Round to 2 dp (display)f"{x:.2f}"x.toFixed(2)String.format("%.2f", x)
Object → JSONjson.dumps(obj)JSON.stringify(obj)mapper.writeValueAsString(obj)
JSON → objectjson.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

TaskPythonJavaScriptJava
Lengthlen(s)s.lengths.length()
Upper / lower cases.upper() / s.lower()s.toUpperCase() / s.toLowerCase()s.toUpperCase() / s.toLowerCase(Locale.ROOT)
Trim whitespaces.strip()s.trim()s.strip()
Contains"x" in ss.includes("x")s.contains("x")
Starts withs.startswith("x")s.startsWith("x")s.startsWith("x")
Replace alls.replace("a", "b")s.replaceAll("a", "b")s.replace("a", "b")
Splits.split(",")s.split(",")s.split(",") (regex!)
Join",".join(items)items.join(",")String.join(",", items)
Reverses[::-1][...s].reverse().join("")new StringBuilder(s).reverse().toString()
Formatf"{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

TaskPythonJavaScriptJava
Sort numberssorted(xs)xs.toSorted((a, b) => a - b)xs.stream().sorted().toList()
Sort by fieldsorted(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()
Sumsum(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 elementxs[-1]xs.at(-1)xs.get(xs.size() - 1) (or getLast() on Java 21+)
Containsx in xsxs.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

TaskPythonJavaScriptJava
Key existsk in dObject.hasOwn(o, k) / m.has(k)m.containsKey(k)
Get with defaultd.get(k, 0)o[k] ?? 0m.getOrDefault(k, 0)
Merge (right wins)a | b{ ...a, ...b }var m = new HashMap<>(a); m.putAll(b);
Iterate pairsfor k, v in d.items():for (const [k, v] of Object.entries(o))for (var e : m.entrySet())
Count occurrencesCounter(xs)xs.reduce((m, x) => m.set(x, (m.get(x) ?? 0) + 1), new Map())xs.stream().collect(groupingBy(x -> x, counting()))
Deep copycopy.deepcopy(d)structuredClone(o)copy constructor / serialisation

Full guides: checking for keys · merging · deep vs shallow copies.

Files, dates and the environment

TaskPythonJavaScript (Node.js)Java
Read whole filePath("f").read_text(encoding="utf-8")fs.readFileSync("f", "utf8")Files.readString(Path.of("f"))
Read line by linefor line in open("f", encoding="utf-8"):readline + for awaitFiles.lines(Path.of("f"))
Current UTC timedatetime.now(timezone.utc)new Date().toISOString()Instant.now()
Unix timestamptime.time() (seconds)Date.now() (milliseconds)Instant.now().getEpochSecond()
Environment variableos.environ.get("KEY")process.env.KEYSystem.getenv("KEY")
Sleep 1 secondtime.sleep(1)await new Promise((r) => setTimeout(r, 1000))Thread.sleep(1000)
Working directoryos.getcwd()process.cwd()System.getProperty("user.dir")

Full guides: reading files · dates and time zones.

Randomness and IDs

TaskPythonJavaScriptJava
Random int 1–6 inclusiverandom.randint(1, 6)Math.floor(Math.random() * 6) + 1ThreadLocalRandom.current().nextInt(1, 7)
Random choicerandom.choice(xs)xs[Math.floor(Math.random() * xs.length)]xs.get(ThreadLocalRandom.current().nextInt(xs.size()))
Shufflerandom.shuffle(xs) (in place)Fisher–Yates loopCollections.shuffle(xs)
UUIDuuid.uuid4()crypto.randomUUID()UUID.randomUUID()
Secure tokensecrets.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

TaskCommand
Undo last commit, keep changesgit reset --soft HEAD~1
Undo a pushed commitgit revert HEAD
Fix last commit messagegit commit --amend -m "..."
Abort a conflicted mergegit merge --abort
Find the commit that broke somethinggit 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.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy