Saturday, October 24, 2015

Count frequency of all characters in String

Count frequency of all characters in String

In this String relation question we are supposed to find the frequency of every character that comes in String.

For example:

Input
Output
null
NullPointerException
“”

“laptop”
l=1, a=1, p=2, t=1, o=1
“mississippi”
m=1, i=4, s=4, p=2
“God”
G=1, o=1, d=1

We will solve this problem using 3 ways. By HashMap, LinkedHashMap and by array.

Solution 1: We will first use HashMap for our solution. We will scan entire String character by character and insert them in HashMap. If the character does not exist in it then we will set value to 1. If it exists then we will add 1 to the previous value.
We will use input String str = "mississippi";

public static
Map<Character, Integer> characterCountByHashMap(String str) {

      if (str == null) {
            throw new NullPointerException("Parameter is null");
      } else if (str.length() == 0) {
            return new HashMap<>();
      }
      Map<Character, Integer> map = new HashMap<Character, Integer>();
      for (Character ch : str.toCharArray()) {

            if (map.containsKey(ch)) {
                  map.put(ch, map.get(ch) + 1);
            } else {
                  map.put(ch, 1);
            }
      }
      System.out.println(map);
      return map;
}

Output:
{p=2, s=4, i=4, m=1}

HashMap does not maintain the order of insertion. To do so we can replace HashMap with LinkedHashMap.

Solution 2: Below the solution implemented by LinkedHashMap.

public static
Map<Character, Integer> characterCountByLinkedHashMap(String str) {

      if (str == null) {
         throw new NullPointerException("Parameter is null");
      } else if (str.length() == 0) {
         return new LinkedHashMap<>();
      }
     Map<Character, Integer> map = new LinkedHashMap<Character, Integer>();
      for (Character ch : str.toCharArray()) {

            if (map.containsKey(ch)) {
                 map.put(ch, map.get(ch) + 1);
            } else {
                 map.put(ch, 1);
            }
       }
       return map;
}

Output:
{m=1, i=4, s=4, p=2}


Solution 3:Now, let us implement this solution by array. We will declare the array of int[] of length 256. Why 256? Because the length of ASCII is 256. We will increment the ASCII location of that character every time. As array provides random or index-based access we can directly reach that the location and increment the counter.

/**
 * We are declaring int[] of 256 because ASCII length is 256.
 * */
public static int[] characterCountByArray(String str) {

      if (str == null) {
            throw new NullPointerException("Parameter is null");
      } else if (str.length() == 0) {
            return new int[] {};
      }
      int[] aux = new int[256];
      for (int i = 0; i < str.length(); i++) {
            aux[str.charAt(i)]++;
      }
      return aux;
}
  
Output
i 4
m 1
p 2
s 4

Below is the entire program that uses HashMap, LinkedHashMap and int[] array.

package com.learninghorizon.blog.strings;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class CharacterCount {

      public static void main(String[] args) {

            String str = "mississippi";
            System.out.println(characterCountByHashMap(str));
            System.out.println();
           
            System.out.println(characterCountByLinkedHashMap(str));
            System.out.println();
           
            int[] aux = characterCountByArray(str);
            for (int i = 0; i < aux.length; i++) {
                  if (aux[i] > 0) {
                        System.out.println((char)i + " " + aux[i]);
                  }
            }
      }

      public static
Map<Character, Integer> characterCountByHashMap(String str) {

            if (str == null) {
               throw new NullPointerException("Parameter is null");
            } else if (str.length() == 0) {
                  return new HashMap<>();
            }
           Map<Character, Integer> map = new HashMap<Character, Integer>();
            for (Character ch : str.toCharArray()) {

                  if (map.containsKey(ch)) {
                        map.put(ch, map.get(ch) + 1);
                  } else {
                        map.put(ch, 1);
                  }
            }
            System.out.println(map);
            return map;
      }

      public static
Map<Character, Integer> characterCountByLinkedHashMap(String str) {

            if (str == null) {
               throw new NullPointerException("Parameter is null");
            } else if (str.length() == 0) {
                  return new LinkedHashMap<>();
            }
     Map<Character, Integer> map = new LinkedHashMap<Character, Integer>();
            for (Character ch : str.toCharArray()) {

                  if (map.containsKey(ch)) {
                        map.put(ch, map.get(ch) + 1);
                  } else {
                        map.put(ch, 1);
                  }
            }
            return map;
      }
     
      /**
       * We are declaring int[] of 256 because ASCII length is 256.
       * */
      public static int[] characterCountByArray(String str) {

            if (str == null) {
               throw new NullPointerException("Parameter is null");
            } else if (str.length() == 0) {
                  return new int[] {};
            }
            int[] aux = new int[256];
            for (int i = 0; i < str.length(); i++) {
                  aux[str.charAt(i)]++;
            }
            return aux;
      }
}


Read how to traverse Map in 5 ways. Check if 2 Strings are anagrams of each other 4 ways.  Find first non-repeating character in String. Reverse a String in 4 different ways.

ArrayList class removeIf method

ArrayList class removeIf method

This is 17th post in series of ArrayList class. Previously we have seen ArrayList introduction, ArrayList class constructors, add() method, addAll() method, clear() method, indexOf() method, contains() method, forEach() method, get(), isEmpty(), iterator(), lastIndexOf() method, listIterator(), remove(int index), remove(Object o) and removeAll(Collection<?> c) method.

In this post we will see removeIf(Predicate<? super E> filter) method. removeIf() method is new method added in Java 8. To understand this method you need to know about lambda operator and Predicate Interface. You also need to know what Functional Interface is. I have attached links so it would be useful for you to read about it.

If you are reading this line that I assume that you have gone through above links.

Below is the program that uses Predicate as anonymous inner class and as Lambda Operator.

package org.example.collections.list.arraylist;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class ArrayListRemoveIf {

      public List<String> names() {
            List<String> names = new ArrayList<String>();
            names.add("Ned");
            names.add("Catelyn");
            names.add("Rob");
            names.add("Arya");
            names.add("Sansa");
            return names;
      }

      /**
       * removeIf() method using Anonymous Inner Class.
       * */
      public void removeIfDemoAnonymousInnerClass(List<String> names) {

            System.out.println("names before removeIf " + names);

            names.removeIf(new Predicate<String>() {
                  @Override
                  public boolean test(String name) {
                        return name.length() > 3;
                  }
            });

            System.out.println("names after removeIf " + names);

      }

      /**
       * removeIf() method using Lambda Operator.
       * */
      public void removeIfDemoLambdaOperator(List<String> names){

            System.out.println("names before removeIf " + names);

            names.removeIf(name -> name.length() > 3);

            System.out.println("names after removeIf " + names);

      }
     
      public static void main(String[] args) {
            ArrayListRemoveIf removeIfDemo = new ArrayListRemoveIf();
            System.out.println("Call by Anonymous Inner Class");
            List<String> names = removeIfDemo.names();
            removeIfDemo.removeIfDemoAnonymousInnerClass(names);
           
            System.out.println("\nCall by Lambda Operator");
           
            names = removeIfDemo.names();
            removeIfDemo.removeIfDemoLambdaOperator(names);
      }
}

Output

Call by Anonymous Inner Class
names before removeIf [Ned, Catelyn, Rob, Arya, Sansa]
names after removeIf [Ned, Rob]

Call by Lambda Operator
names before removeIf [Ned, Catelyn, Rob, Arya, Sansa]
names after removeIf [Ned, Rob]


That’s all on removeIf() method . In next post we will see method replaceAll(UnaryOperator<E> operator) method. It is new method added in Java 8.

ArrayList class removeAll(Collection) method

ArrayList class removeAll method

This is 16th post in series of ArrayList class. Previously we have seen ArrayList introduction, ArrayList class constructors, add() method, addAll() method, clear() method, indexOf() method, contains() method, forEach() method, get(), isEmpty(), iterator(), lastIndexOf() method, listIterator(), remove(int index), remove(Object o) method.

In this post we will see removeAll(Collection<?> c) method. removeAll(Collection<?> c) method is used to remove all the elements from this list that are contained in specified Collection(as parameter).

I have written a small program to demonstrate the usage of removeAll(Collection<?> c) method.

package org.example.collections.list.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListRemoveAll {

      /**
       * List<String> that contains names
       * */
      public List<String> names() {
            List<String> names = new ArrayList<String>();
            names.add("Ned");
            names.add("Catelyn");
            names.add("Rob");
            names.add("Arya");
            names.add("Sansa");
            return names;
      }

      /**
       * List<String> contains those names that are
       * to be removed.
       * */
      public List<String> namesToBeRemoved() {
            List<String> names = new ArrayList<String>();
            names.add("Ned");
            names.add("Rob");
            names.add("Arya");
            return names;
      }

      /**
       * names List will remove elements that are contained in
       * namesToBeRemoved List.
       * */
      public void removeAllDemo(List<String> names,
  List<String> namesToBeRemoved) {

       names.removeAll(namesToBeRemoved);
       System.out.print("After names.removeAll(namesToBeRemoved) call: ");
       System.out.println(names);

      }

      public static void main(String[] args) {
            ArrayListRemoveAll removeAll = new ArrayListRemoveAll();
            List<String> names = removeAll.names();
            System.out.println("Names: " + names);
            List<String> namesToBeRemoved = removeAll.namesToBeRemoved();
            System.out.println("Names to be removed: " + namesToBeRemoved);
            removeAll.removeAllDemo(names, namesToBeRemoved);
      }
}

Output
Names: [Ned, Catelyn, Rob, Arya, Sansa]
Names to be removed: [Ned, Rob, Arya]
After names.removeAll(namesToBeRemoved) call: [Catelyn, Sansa]


See in output we can see that Ned, Rob, Arya are removed this list. Now list only contains Catelyn, Sansa.

That’s all for removeAll(Collection<?> c) method.

In next post we will removeIf(Predicate<? Super E> filter) method. This method is part of Java 8(interfaces) and uses Predicate Interface to filter the elements from the List.




Ads Inside Post