Pacific-Design.com

    
Home Index

1. Algorithms

2. Group By Key

+ PrettyMap

Algorithms / Group By Key /

Group by first 3 chars as key

import java.util.*;

public class GroupByKey {

    /*------------------------------------------------------------------------*/
    public static Map groupBy(String input[]) {

        Map map = new TreeMap<>();

        for (String str : input) {

            String key = str.substring(0, 3);
            String value = map.get(key);

            if (value != null) {
                map.put(key, value + "|" + str);
            } else {
                map.put(key, str);
            }
        }
        return map;
    }
    /*------------------------------------------------------------------------*/
    public static void main(String args[]) {

        String input[] = { "data", "book", "booking", "science", "database" };
        Map map = groupBy(input);
        System.out.println(map);
    }
    /*------------------------------------------------------------------------*/