Tuesday, May 20, 2014

Java Map/Collections Cheat Sheet : Simply 'When and What to use'?

This is a notoriously simple when and what to use Java collection API cheat sheet, containing most common implementations.

Monday, May 19, 2014

Find the occurrence of words in a given string

IDEONE: http://ideone.com/9SENHc
package com.learning.collection;
import java.util.*;
/**
 * Count frequency of words occurring in a string
 */
public class MapExample {
    public static void main(String[] args){
        String str = "ika pika ting tong ting tong me";
        String[] strr = str.split("\\s");
        workMap(strr);
    }

    static void workMap(String...words){
        Map map = new HashMap();
        Integer ONE = new Integer(1);

        for(String word : words){
            Integer frequency = (Integer)map.get(word);
            /*
            'frequency' is the count of the words.
            For a new word getting added to the Map, we set its frequency as 1.
            For existing words, we take their existing frequency (value in the map)
            and increment it and put back into the map correspondint to that word (key in the map)
             */
            frequency = (frequency == null) ? ONE : new Integer(frequency.intValue() + 1);
            map.put(word, frequency);
        }
        System.out.println("Unsorted:");
        System.out.println(map);

        Map sortedMap = new TreeMap(map);
        System.out.println("Sorted:");
        System.out.println(sortedMap);
    }
}
Output:
Unsorted: {ika=1, pika=1, ting=2, tong=2, me=1}
Sorted: {ika=1, me=1, pika=1, ting=2, tong=2}


--Suggestion by Dr. Heinz Kabutz (Java Champion)
How you would count words in Java 8 :-) And if you want to do it in parallel, just add parallel() into the stream...
import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class MapExample {
  public static void main(String[] args) {
    String str = "hello world how are you how is life i am into ascent";

    Map<String, Integer> map = Arrays.stream(str.split("\\s"))
        .collect(Collectors.toMap(
            Function.identity(),
            n -> 1,
            (n1, n2) -> n1 + n2,
            TreeMap::new));
    System.out.println("map = " + map);
  }
}