[Java edition] My favorite code snippets everyone should know

To save time during technical interviews or time limited coding tasks it's better to memorize such statements, to not wast time every time on googling it.

Some of them may look silly but I always had hard time remembering it.

Based on my experience I found following snippets inclredible usefull:

Arrays.toString(array)

List of strings to array of strings:

list.toArray(new String[0]);

Sort 2d array by inner array's element

Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);//desc
Arrays.sort(twoDim, (a1,a2) -> a1[0] - a2[0]);//asc

Sort array of strings by length

Arrays.sort(strings, Comparator.comparing(s -> s.length()));

Create max-heap

PriorityQueue<Integer> maxPQ = new PriorityQueue<Integer>(Collections.reverseOrder());

Copy an array (clone an array)

Arrays.copyOf(a, a.length);
Arrays.copyOfRange(original, int from, int to);//to is exclusive
Integer.toBinaryString(i)

String to array of characters

str.toCharArray();

Convert array of integers to a list

Arrays.stream(array).boxed().collect(Collectors.toList())
Comments (4)