Tuesday, July 6, 2010

JAVA: Convert String to InputStream

You can use ByteArrayInputStream to convert String to InputStream.
ByteArrayInputStream extends InputStream.

Example:
String content = "Convert string to inputstream";
ByteArrayInputStream stream = new ByteArrayInputStream(content.getBytes());



Reference:
1. http://forums.sun.com/thread.jspa?threadID=670188

2. http://java.sun.com/j2se/1.4.2/docs/api/java/io/ByteArrayInputStream.html

Wednesday, May 12, 2010

JSTL: Find length of a collection

To get a length of a collection:
${fn:length(tvPackageGroup.addonOptions)}

Include <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> namespace.
http://stackoverflow.com/questions/851880/check-a-collection-size-with-jstl

Sorting a collection in JSTL

javadoc: http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/fn/tld-summary.html

Tuesday, February 2, 2010

JAVA: reverse string interview question

When you go for an interview, lot of companies ask String manipulation questions.


Some of the most common questions are:

  • Reverse words in a string (words are separated by spaces) - Most Common
  • Reverse String
  • Revers the order of words

I have written a code that performs all these functions. Hope this will help you.

/**
* Created by IntelliJ IDEA.
* User: priyank
* Date: Feb 2, 2010
*/
public class StringTest {

public static void main(String[] args) {
String str = "My name is khan";
// String result = reverseString(str);
// String result = reverseWords(str);
// String result = reverseSequence(str);
String result = iReverseSequence(str);

System.out.println(result);
}

static String reverseString(String str) {
char[] ch = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i=(ch.length-1);i>=0;i--) {
sb.append(ch[i]);
}
return sb.toString();
}

static String reverseWords(String str) {
String[] st = str.split("\\s");
StringBuilder sb = new StringBuilder();
for(int i=0; i < st.length;i++) {
sb.append(reverseString(st[i])+" ");
}
return sb.toString();
}

static String reverseSequence(String str) {
String[] st = str.split("\\s");
StringBuilder sb = new StringBuilder();
for(int i=(st.length-1);i>=0;i--) {
sb.append(st[i]+" ");
}
return sb.toString();
}


// Without using inbuilt java functions (for ex without using split())
// I still used substr() though
static String iReverseSequence(String str) {
String word = "";
int lastIndex = str.length();
for(int i=(str.length()-1);i>=0;i--) {
if(str.charAt(i) == ' ') {
word += str.substring(i+1,lastIndex)+" ";
lastIndex = i;
}
}
word += str.substring(0,lastIndex);
return word;
}
}