Useful for string set lookups and command completion stuff : Tree « Collections Data Structure « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JDK 6
25.JNDI LDAP
26.JPA
27.JSP
28.JSTL
29.Language Basics
30.Network Protocol
31.PDF RTF
32.Reflection
33.Regular Expressions
34.Scripting
35.Security
36.Servlets
37.Spring
38.Swing Components
39.Swing JFC
40.SWT JFace Eclipse
41.Threads
42.Tiny Application
43.Velocity
44.Web Services SOA
45.XML
Java » Collections Data Structure » TreeScreenshots 
Useful for string set lookups and command completion stuff
     

//package com.ryanm.util.text;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Useful for string set lookups and command completion stuff
 
 @author ryanm
 */
public class RadixTree
{
  private Node root = new Node"" );

  private final boolean caseSensitive;

  /**
   @param caseSensitive
   *           <code>true</code> if case matters. Note that a
   *           case-insensitive {@link RadixTree} will convert all
   *           strings passed to it for insertion or query to lower
   *           case.
   */
  public RadixTreeboolean caseSensitive )
  {
    this.caseSensitive = caseSensitive;
    root.isString = false;
  }

  /**
   * Adds string to the set
   
   @param string
   */
  public void addCharSequence string )
  {
    if!caseSensitive )
    {
      string = string.toString().toLowerCase();
    }

    root.addStringstring );
  }

  /**
   * Removes a string from the set
   
   @param string
   */
  public void removeCharSequence string )
  {
    if!caseSensitive )
    {
      string = string.toString().toLowerCase();
    }

    root.removeStringstring );
  }

  /**
   * Tests if the string is contained in the set
   
   @param string
   @return <code>true</code> if the entire string is contained in
   *         the tree
   */
  public boolean containsCharSequence string )
  {
    if!caseSensitive )
    {
      string = string.toString().toLowerCase();
    }

    return findPredecessorstring ).length() == string.length();
  }

  /**
   * Finds the substring of the string that is in the set
   
   @param string
   @return The substring that belongs
   */
  public String findPredecessorCharSequence string )
  {
    if!caseSensitive )
    {
      string = string.toString().toLowerCase();
    }

    StringBuilder buff = new StringBuilder();
    root.findPredecessorstring, buff );

    return buff.toString();
  }

  /**
   * Finds possible completions that fit in the set
   
   @param string
   @param depth
   *           How deeply to search the tree, the maximum number of
   *           decisions that need to be made to type any one
   *           completion
   @return A list of possible completions
   */
  public List<String> findSuccessorsCharSequence string, int depth )
  {
    if!caseSensitive )
    {
      string = string.toString().toLowerCase();
    }

    List<String> completions = new LinkedList<String>();

    root.findSuccessorsstring, depth, completions );

    return completions;
  }

  @Override
  public String toString()
  {
    StringBuilder buff = new StringBuilder();

    root.buildStringbuff, -);

    return buff.toString();
  }

  private class Node implements Comparable<Node>
  {
    private CharSequence value;

    private Node[] children = new Node];

    /**
     * Indicates that the string ending at this node is a string in
     * the set
     */
    private boolean isString = true;

    private NodeCharSequence string )
    {
      value = string;
    }

    private void findSuccessorsCharSequence string, int depth, List<String> completions )
    {
      int d = findDivergenceIndexstring );

      ifd < value.length() || d == string.length() )
      {
        StringBuilder prefix = new StringBuildervalue.subSequenced, value.length() ) );

        ifisString )
        {
          completions.addprefix.toString() );
        }

        ifdepth > )
        {
          forint i = 0; i < children.length; i++ )
          {
            children].getCompletionsprefix, depth - 1, completions );
          }
        }
      }
      else
      {
        Node c = findChildstring.charAt) );

        ifc != null )
        {
          c.findSuccessorsstring.subSequenced, string.length() ), depth, completions );
        }
      }
    }

    private void getCompletionsStringBuilder prefix, int depth, List<String> completions )
    {
      int pl = prefix.length();
      prefix.appendvalue );

      ifisString )
      {
        completions.addprefix.toString() );
      }

      ifdepth > )
      {
        forint i = 0; i < children.length; i++ )
        {
          children].getCompletionsprefix, depth - 1, completions );
        }
      }

      prefix.deletepl, prefix.length() );
    }

    private void addStringCharSequence string )
    {
      int d = findDivergenceIndexstring );

      ifd < value.length() )
      {
        // need to split this node
        Node child = new Nodevalue.subSequenced, value.length() ) );
        child.children = children;
        child.isString = isString;
        value = value.subSequence0, d );
        children = new Node[] { child };
        isString = false;
      }

      ifd == string.length() && d > )
      {
        isString = true;
      }
      else
      {
        Node c = findChildstring.charAt) );

        ifc != null )
        {
          c.addStringstring.subSequenced, string.length() ) );
        }
        else
        {
          insertNodenew Nodestring.subSequenced, string.length() ) ) );
        }
      }
    }

    private void removeStringCharSequence string )
    {
      int d = findDivergenceIndexstring );

      ifd == value.length() && d == string.length() )
      {
        isString = false;

        ifchildren.length == )
        // unify nodes
          StringBuilder buff = new StringBuildervalue );
          buff.appendchildren].value );
          value = buff;
          isString = children].isString;
          children = children].children;
        }
      }
      else
      {
        ifd == value.length() )
        {
          // check children
          Node c = findChildstring.charAt) );
          ifc != null )
          {
            c.removeStringstring.subSequenced, string.length() ) );
          }
        }
      }
    }

    private void findPredecessorCharSequence string, StringBuilder buff )
    {
      int d = findDivergenceIndexstring );

      ifd == value.length() && d <= string.length() )
      // this entire node was in the tree and there still some
        // to go
        buff.appendvalue.subSequence0, d ) );

        // check children
        ifd < string.length() )
        {
          CharSequence c = string.subSequenced, string.length() );

          Node child = findChildc.charAt) );
          child.findPredecessorc, buff );
        }
      }
    }

    private Node findChildchar )
    {
      forint i = 0; i < children.length; i++ )
      {
        ifc == children].value.charAt) )
        {
          return children];
        }
      }

      return null;
    }

    private int findDivergenceIndexCharSequence string )
    {
      int d = 0;
      whiled < value.length() && d < string.length() && value.charAt== string.charAt) )
      {
        d++;
      }
      return d;
    }

    private void insertNodeNode child )
    {
      int i = Arrays.binarySearchchildren, child );
      assert i < 0;

      i += 1;
      i = -i;

      Node[] nc = new Nodechildren.length + ];

      System.arraycopychildren, 0, nc, 0, i );

      nc= child;

      ifi < nc.length )
      {
        System.arraycopychildren, i, nc, i + 1, children.length - i );
      }

      children = nc;
    }

    @Override
    public int compareToNode o )
    {
      return TextUtils.compareTovalue, o.value );
    }

    private void buildStringStringBuilder buff, int indent )
    {
      forint i = 0; i < indent; i++ )
      {
        buff.append" " );
      }

      ifisString )
      {
        buff.append"\"" );
      }
      buff.appendvalue );
      ifisString )
      {
        buff.append"\"" );
      }

      indent++;

      forint i = 0; i < children.length; i++ )
      {
        buff.append"\n" );
        children].buildStringbuff, indent );
      }
    }
  }
}

/**
 * Utility methods for dealing with text
 
 @author ryanm
 */
class TextUtils
{
  /**
   * Tests if s starts with t, ignoring the case of the characters
   
   @param s
   @param t
   @return <code>true</code> if s.toLowerCase().equals(
   *         t.toLowerCase() ), but more efficiently
   */
  public static boolean startsWithIgnoreCaseCharSequence s, CharSequence t )
  {
    ifs.length() < t.length() )
    {
      return false;
    }

    forint i = 0; i < t.length(); i++ )
    {
      char slc = Character.toLowerCases.charAt) );
      char tlc = Character.toLowerCaset.charAt) );
      ifslc != tlc )
      {
        return false;
      }
    }
    return true;
  }

  /**
   * See {@link String#compareToIgnoreCase(String)}
   
   @param s
   @param t
   @return See {@link String#compareToIgnoreCase(String)}
   */
  public static int compareToIgnoreCaseCharSequence s, CharSequence t )
  {
    int i = 0;

    whilei < s.length() && i < t.length() )
    {
      char a = Character.toLowerCases.charAt) );
      char b = Character.toLowerCaset.charAt) );

      int diff = a - b;

      ifdiff != )
      {
        return diff;
      }

      i++;
    }

    return s.length() - t.length();
  }

  /**
   * See {@link String#compareTo(String)}
   
   @param s
   @param t
   @return See {@link String#compareTo(String)}
   */
  public static int compareToCharSequence s, CharSequence t )
  {
    int i = 0;

    whilei < s.length() && i < t.length() )
    {
      char a = s.charAt);
      char b = t.charAt);

      int diff = a - b;

      ifdiff != )
      {
        return diff;
      }

      i++;
    }

    return s.length() - t.length();
  }

  /**
   * Splits a string
   
   @param composite
   *           The composite string
   @param leftBracket
   *           the opening parenthesis character
   @param rightBracket
   *           the closing parenthesis character
   @param separator
   *           The character that separates tokens. Separators that
   *           lie between at least one pair of parenthesis are
   *           ignored
   @return An array of individual tokens
   */
  public static String[] splitString composite, char leftBracket, char rightBracket,
      char separator )
  {
    List<String> c = new ArrayList<String>();

    int start = 0;
    int i;
    int lbcount = 0;

    fori = 0; i < composite.length(); i++ )
    {
      ifcomposite.charAt== leftBracket )
      {
        lbcount++;
      }
      else ifcomposite.charAt== rightBracket )
      {
        lbcount--;
      }
      else ifcomposite.charAt== separator && lbcount == )
      {
        c.addcomposite.substringstart, i ).trim() );
        start = i + 1;
      }
    }

    c.addcomposite.substringstart, i ).trim() );

    return c.toArraynew Stringc.size() ] );
  }

  /**
   * Wraps the input string in {@code <html></html>} and breaks it up
   * into lines with {@code <br>} elements. Useful for making
   * multi-line tootips and the like.
   
   @param s
   *           The input String
   @param lineLength
   *           The desired length of the output lines.
   @return The HTMLised string
   */
  public static String HTMLiseStringString s, int lineLength )
  {
    ifs != null )
    {
      StringBuilder buff = new StringBuilder);

      int lineStart = 0;

      whilelineStart + lineLength < s.length() )
      {
        // find the first whitespace after the linelength
        int firstSpaceIndex = buff.indexOf" ", lineStart + lineLength );
        // replace it with a <br>
        iffirstSpaceIndex != -)
        {
          buff.deleteCharAtfirstSpaceIndex );
          buff.insertfirstSpaceIndex, "<br>" );
          lineStart = firstSpaceIndex + 4;
        }
        else
        {
          lineStart = s.length();
        }
      }

      buff.insert0"<html>" );
      buff.append"</html>" );

      return buff.toString();
    }

    return null;
  }

}

   
    
    
    
    
  
Related examples in the same category
1.Binary TreeBinary Tree
2.Your own tree with generic user object
3.Tree Node for the for a general tree of Objects
4.A tree structure that maps inheritance hierarchies of classesA tree structure that maps inheritance hierarchies of classes
5.Data structure that mantains data in a ordered binary tree; each node is greater (smaller) or equal than its 2 sub-nodes, for all the hierarchy.Data structure that mantains data in a ordered binary tree; each node is greater (smaller) or equal than its 2 sub-nodes, for all the hierarchy.
6.Tree Node
7.Ternary Search Tree
8.Char Prefix Tree
9.Lightweight tree n-arity structure
10.This class is designed to provide a generic tree that allows duplicates.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.