Friday, April 21, 2017

Best way to convert ArrayList of Character to String

StringBuilder result = new StringBuilder(chars.size());
for (Character c : chars) {
  result.append(c);
}
String output = result.toString();

Removing range (tail) from a List

subList(list.size() - N, list.size()).clear() is the recommended way to remove the last N elements. Indeed, the Javadoc for subList specifically recommends this idiom:
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:
 list.subList(from, to).clear();
Indeed, I suspect that this idiom might be more efficient (albeit by a constant factor) than calling removeLast() N times, just because once it finds the Nth-to-last node, it only needs to update a constant number of pointers in the linked list, rather than updating the pointers of each of the last N nodes one at a time.

How to replace existing value of ArrayList element in java

Use the set method to replace the old value with a new one.
list.set( 2, "New" );
share

Tuesday, April 18, 2017

java split string

Question
What regex pattern would need I to pass to the java.lang.String.split() method to split a String into an Array of substrings using all whitespace characters (' ', '\t', '\n', etc.) as delimiters?
Answer
myString.split("\\s+");
 ------------------------------------
String[] words=s1.split("\\s");//splits the string based on whitespace  

How to read text file line by line in Java code snippet

BufferedReader lineReader = new BufferedReader(new FileReader(filePath));
String lineText = null;
 
List<String> listLines = new ArrayList<String>();
 
while ((lineText = lineReader.readLine()) != null) {
    listLines.add(lineText);
}
 
lineReader.close();