Java CheatSheet for Developers

java cheatsheet

In this post I will keep some useful Java hacks and one-liners which are useful in every day programming

Multiple Each Item in a List by 2

IntStream.range(1, 10).map(i -> i * 2);

Sum a List of Numbers

IntStream.range(1, 100).sum();

Verify if String exists in a List

List wordList = Arrays.asList("Maven", "jdk", "JBoss", "java");
String tweet = "This is a JBoss tutorial";
wordList.stream().anyMatch(str::contains);

Create a Map where keys are “true” if > 50

Map<Boolean, List<Integer>> passedFailedMap = Stream.of(29, 18, 76, 82, 50, 88).collect(Collectors.partitioningBy(i -> i > 50));
System.out.println(passedFailedMap);
//{false=[29, 18, 50], true=[76, 82, 88]}

Find minimum (or maximum) in a List:

IntStream.of(24, 45, -3, 26, 18).min();
Arrays.asList(24, 45, -3, 26, 18).stream().min(Integer::compare);
Arrays.asList(24, 45, -3, 26, 18).stream().reduce(Integer::min);
Collections.min(Arrays.asList(24, 45, -3, 26, 18));

Sorted List by HashMap keys:

SortedSet keys = new TreeSet(myHashMap.keySet());

Sorted List by HashMap values:

SortedSet values = new TreeSet(myHashMap.values());

Sorting ArrayList in ascending Order

Collections.sort(list);

Random String

String uuid = UUID.randomUUID().toString();

Parallel Processing

List dataList = null;
dataList.parallelStream().map(line -> processItem(line));

Read a File in one line

String fileText = new String(Files.readAllBytes(Paths.get("data.txt")));
List fileLines = Files.readAllLines(Paths.get("data.txt"));

Java CheatSheet – by Mastertheboss (2022). Read more CheatSheets.