Java syntax

whitehousechef·2025년 5월 12일

int()

Integer.parseInt()

maths

so dividing int with int gives us int

but int divided with double gives us floating numbers with dp

double average = sum / (double) count

collection.toArray()

Collections (Set, List, etc.) are not arrays
Sets have no indexes → You can't do mySet[0] or mySet.get(0)
Arrays have indexes → You can do myArray[0]
.toArray() converts collection → array for indexed access

Set<String> set = Set.of("A", "B", "C");
String[] array = set.toArray(new String[0]);

// Java does this:
// 1. Sees you want String[] (from new String[0])
// 2. Creates new String[3] (right size)
// 3. Copies all set elements to array
// 4. Returns the new array

graph

when making a graph, u should make double list int graph and for each index add a new ArrayList like

also its not graph[].append() like python but its get() like graph.get().add()

        List<List<Integer>> graph = new ArrayList<>();
        for(int i=0; i<n;i++) graph.add(new ArrayList<>());

        for(int[] pre: prerequisites){
            int before = pre[1], after = pre[0];
            indegree[after]+=1;
            graph.get(before).add(after);
        }

also we cant do

0<=next_row<m for java

It should be 
0<=next_row && next_row<m

backtracking

we cannot do
ans.add(my_temp_list)

this adds just the reference to the temp list, not the actual list. Instead wat we should do is

ans.add(new ArrayList<>(so_far));
so_far.remove(so_far.size() - 1);

string

str()

String.valueOf()

sort string

u first have to convert string into char array then sort then convert back to string using new String(arr)

char[] arr = word.toCharArray();   // step 1: fill char[] with chars of word
Arrays.sort(arr);                  // step 2: sort it
String newWord = new String(arr);  // step 3: convert back to String
System.out.println(newWord);

string split

if wanna splti without space u have to put parameter as ""

String[] hi = hola.split("");

.compareTo()

compares strings lexicographically.

It gives negative value if first string comes alphabetically FIRST before the second string

"ab".compareTo("ba")  // Returns negative (ab < ba)
"ba".compareTo("ab")  // Returns positive (ba > ab) 
"ab".compareTo("ab")  // Returns 0 (equal)

.substring(start_idx,end_idx)

instead of slicing string in py, u have to use .substring() in java

char to number

char c = '5';
int val = c - '0'; // Result: 5

list.add() not list.append()

unlike py which is append(), in java it is add() for List<>

add list to list with Arrays.asList()

                    // List<Integer> tmp = new ArrayList<>();
                    // tmp.add(nums[i]);
                    // tmp.add(nums[left]);
                    // tmp.add(nums[right]);
                    // ans.add(new ArrayList<>(tmp));
                    ans.add(Arrays.asList(nums[i],nums[left],nums[right]));

length() vs length vs size()

length() is for string.
length is for arrays.
size() is for lists.

getting value by index for list vs array

list is using .get()
array is using nums[]

List sort and reverse

Collections.sort(numbers)
Collections.sort(numbers, Collections.reverseOrder());

Double list sort and reverse

        // Sort by the first element of each inner list
        graph.sort((a, b) -> Integer.compare(a.get(0), b.get(0)));

list & array lambda sort on certain index

using comparator

List<int[]> edges = new ArrayList<>();
edges.sort(Comparator.comparingInt(edge->edge[2]));
edges.sort(Comparator.comparingInt(edge -> edge[2]).reversed());

slicing array

Arrays.copyOfRange(array, inclusive starting idx, exclusive end index)

This is useful for DFS

import java.util.Arrays;

public class ArraySlice {
    public static void main(String[] args) {
        int[] originalArray = {1, 2, 3, 4, 5, 6, 7, 8};
        
        // Calculate the middle index
        int middleIndex = originalArray.length / 2;
        
        // Slice the first half
        int[] firstHalf = Arrays.copyOfRange(originalArray, 0, middleIndex);
        
        // Slice the second half
        int[] secondHalf = Arrays.copyOfRange(originalArray, middleIndex, originalArray.length);
        
        System.out.println("Original array: " + Arrays.toString(originalArray));
        System.out.println("First half: " + Arrays.toString(firstHalf));
        System.out.println("Second half: " + Arrays.toString(secondHalf));
    }
}

array sum

int[] arr = {1, 2, 3, 4, 5};
int sum = Arrays.stream(arr).sum(); // sum is 15

concat arrays together

useful for dfs when u find base condition and u wanna rebuild the array

int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};

int[] combined = new int[array1.length + array2.length];

System.arraycopy(array1, 0, combined, 0, array1.length);
System.arraycopy(array2, 0, combined, array1.length, array2.length);

// The combined array will be {1, 2, 3, 4, 5, 6}

//or
import java.util.stream.IntStream;

int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};

int[] combined = IntStream.concat(Arrays.stream(array1), Arrays.stream(array2))
                          .toArray();

// The combined array will be {1, 2, 3, 4, 5, 6}

array sort and reverse

Arrays.sort(numbers);
System.out.println("Ascending Sorted Array: " + Arrays.toString(numbers)); // Output: [1, 2, 5, 8, 9]

// Reverse the array
        // int[] 배열을 Integer[] 배열로 변환
        Integer[] integerArray = new Integer[hia.length];
        for (int i = 0; i < hia.length; i++) {
            integerArray[i] = hia[i];
        }
// 배열을 내림차순으로 정렬
        Arrays.sort(integerArray, Collections.reverseOrder());
        System.out.println(Arrays.toString(integerArray));
        int[] intArray = new int[integerArray.length];
for (int i = 0; i < integerArray.length; i++) {
    intArray[i] = integerArray[i];
}

array sort if its int[][] 2d

also notice we need to use .deepToString() for 2d arrays.

        // Sort by start time
        Arrays.sort(appointments, (a, b) -> Integer.compare(a[0], b[0]));
        System.out.println(Arrays.deepToString(appointments));

Arrays.toString() vs .deepToString()

Arrays.toString() → works nicely for 1D arrays (like int[])

Arrays.deepToString() → is needed for nested arrays (like int[][])

convert array to list

convert int array to list

I thought Arrays.asList(my int array) will do the trick but nope.When we try adding that we will get List<int[]> not list of list.

Arrays.asList(ele1,ele2) will work but not for an entire array.

        int[] intArray = {10, 20, 30};
        List<Integer> integerList = new ArrayList<>();

        for (int value : intArray) {
            integerList.add(value); // Autoboxing from int to Integer happens automatically here
        }

convert list to array

convert int list to array

list.stream().mapToInt(Integer::intValue).toArray();

or using for loop like

        List<Integer> integerList = new ArrayList<>();

        // 1. Create an int[] array of the same size as the List
        int[] intArray = new int[integerList.size()];

        // 2. Iterate through the List and populate the array
        for (int i = 0; i < integerList.size(); i++) {
            // Get the Integer object from the List and unbox it to an int
            intArray[i] = integerList.get(i);
        }

convert char list to array

        List<Character> charList = Arrays.asList('a', 'b', 'c', 'd');
        
        char[] charArray2 = new char[charList.size()];
        for (int i = 0; i < charList.size(); i++) {
            charArray2[i] = charList.get(i); // Auto-unboxing
        }
        System.out.println("char[] using streams: " + Arrays.toString(charArray));

List<int[]> to int[][] with .toArray()

        List<int[]> result = new ArrayList<>();
        result.add(new int[]{1, 2});
        result.add(new int[]{3, 4});

        int[][] array = result.toArray(new int[result.size()][]);

dictionary

getOrDefault()

actually this doesnt update the map if key is missing. U have to use computeIfAbsent()

wrong:

map.getOrDefault(new_word, new ArrayList<>()).add(word);

computeIfAbsent()

creates a value if the key is missing.
correct:

            // ensure list exists, then add original word
            map.computeIfAbsent(key, k -> new ArrayList<>()).add(word);

dictionary sort key

you have to make a separate list containing just the keys of dictionary, then iterate through that key

        List<Integer> list = new ArrayList<>(map.keySet());
        Collections.sort(list);
        Collections.sort(list,Collections.reverseOrder());
        
        for(int i:list){
            System.out.println(i);
        }

dictionary sort value

you have to make a separate list containing Map.Entry<t1,t2> of your dictionary's entrySet().

        List<Map.Entry<Integer, int[]>> list1 = new ArrayList<>(map.entrySet());
        Collections.sort(list1, (e1, e2) -> e2.getValue()[1]-e1.getValue()[1]);


        for(Map.Entry<Integer,int[]> entry: list1){
            System.out.println(entry.getKey());
            System.out.println(Arrays.toString(entry.getValue()));
        }

equals()

comparing 2 dictionaries tgt can be done via .equals()

Stack

instantiation

Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.pop();

iterating

just doign a for loop doesnt print the stack from top to bottom. We need to pop elements. If you want to preserve the original stack, we make a clone via .clone().

Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3); // Added another element for better demonstration
        System.out.println("Original Stack: " + stack);

        // Pop operation (as in your example)
        Integer poppedElement = stack.pop();
        System.out.println("Popped Element: " + poppedElement);
        System.out.println("Stack after pop: " + stack);

        System.out.println("\n### Iterating from top to bottom (preserving the stack) ###");
        Stack<Integer> clonedStack = (Stack<Integer>) stack.clone(); // Create a clone
        System.out.println("Cloned Stack: " + clonedStack);

        System.out.println("Iterating by popping from the cloned stack:");
        while (!clonedStack.isEmpty()) {
            Integer element = clonedStack.pop();
            System.out.println(element);

PQ

instant

unlike py it doesnt sort the tuple's 0th index. So We need to put comparator

v impt. When reversing to be max pq, we need to cast the object to whatever type we are storing. But it is not (int[]) a. It is (int[] a)!!

and the below way of for loop to tier through sorted pq doesnt guarantee the sorted order. U should poll it

        PriorityQueue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
        PriorityQueue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt((int[] a) -> a[1]).reversed());
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        queue.offer(new int[]{0,2});
        queue.offer(new int[]{1,1});
        
        ## wrong
        for(int[] a:queue){
            System.out.println(Arrays.toString(a));
        }
        
        ## correct
        while (!queue1.isEmpty()) {
            int[] element = queue1.poll();
            System.out.println(Arrays.toString(element));
        }

0개의 댓글