Core Java: Programming code snippets frequently used

Here are few things I learnt while coding in java:

  1. Increment an occurrence in map
    for(char current : input.toCharArray()){
          count.put(current, count.getOrDefault(current, 0) + 1);
    }
  1. Let’s say you want to decrement the occurrence and when occurrence becomes zero, remove entry.
    char charToRemove = 'c';
    count.put(charToRemove, count.get(charToRemove) - 1);
    count.remove(charToRemove, 0);

  1. Change alphabet case without in-built functions:
    a) Uppercase to Lowercase : (OR with space)
    char currentChar = 'A';         
    char result = (char)(currentChar | ' ');

b) Lowercase to Uppercase : (AND with underscore)

    char currentChar = 'A';         
    char result = (char)(currentChar & '_');
Alternative:
If not good at remembering bitwise operations, then conventional subtracting of ascii value should also do the job.
  1. We often need to return empty Set, List or Map when input is invalid. To make code more readable:
    return Collections.EMPTY_SET;
    return Collections.EMPTY_LIST;
    return Collections.EMPTY_MAP;
  1. Mostly in graph problems we need to add edges between nodes. If node is not created, we first create list for the children and then add edges
    Map<Integer, List<Integer>> graph = new HashMap<>();
    for(int[] edge : edgeList){
        if(graph.containsKey(edge[0]) == false){
            graph.put(edge[0], new ArrayList<>());
        }
        graph.get(edge[0]).add(edge[1]);
    }
 Above code can be abstracted as follows : 
    for(int[] edge : edgeList){
        graph.computeIfAbsent(edge[0], val -> new ArrayList<>()).add(edge[1]);
    }

6. To sort an array/Collections:

Arrays.sort(array, (a,b) ->  a[0] - b[0]); //ascending sorting 2d array based on first index
Arrays.sort(array,(a,b)-> {
            if(a[1]==b[1]) return 0;
            if(a[1]<b[1]) return -1;
            return 1;
        }); //to avoid overflow
       //Sorting map keys
       Map<Integer,Integer> count = new HashMap();
        for(int i : nums){
            count.put(i , count.getOrDefault(i,0)+1);
        }
       List<Integer> candidates = new ArrayList(count.keySet()); 
        Collections.sort(candidates, (w1, w2) -> count.get(w1).equals(count.get(w2)) ?
                w1.compareTo(w2) : count.get(w2) - count.get(w1));

7. Priority Queue

PriorityQueue<Character> pq = new PriorityQueue<>((a, b) -> count[b] - count[a]);
//Places b on top of a in heap
//Max heap
PriorityQueue<Integer> heap = new PriorityQueue<>(Comparator.reverseOrder());

8. Convert an array to list:

Arrays.asList(i,j) 

Leave a Reply

Your email address will not be published. Required fields are marked *