parse array and extract string of same length - java

my first question.
lets say i have arraylist of strings in java
ArrayList<string> s= new ArrayList<string>;
and it contains sorted list by size.
s.add("ab");
s.add("abc");
s.add("aab");
s.add("baab");
s.add("abcd");
what i want to do is, iterate the list and pick group of elements which has same length and put into seprate array of arrays.
Group 1 ab
Group 2 abc,aab and so on...
i am doing this in java please help

Since they're sorted by size already it's easy. Here's one way that works:
ArrayList<ArrayList<String>> listofLists = new ArrayList<ArrayList<String>>();
int length = -1;
for(String str : s) { // where s is your sorted ArrayList of Strings
if(str.length() > length) {
listofLists.add(new ArrayList<String>());
length = str.length();
}
listofLists.get(listofLists.size()-1).add(str);
}
At the end, listofLists will be an ArrayList of ArrayLists containing groups of Strings of the same length. Again, this depends on s (your ArrayList<String>) being sorted by size. Also, String must be capitalized there.

You can use this code "it works as you need"
import java.util.ArrayList;
public class Test{
public static void main(String[] args){
ArrayList<String> s = new ArrayList<String>();
s.add("ab");
s.add("abc");
s.add("aab");
s.add("baab");
s.add("abcd");
String[] group1 = new String[s.size()];
String[] group2 = new String[s.size()];
String[] group3 = new String[s.size()];
for(int i = 0 ; i < s.size() ; i++){
if(s.get(i).length() == 2)
group1[i] = s.get(i);
else if(s.get(i).length() == 3)
group2[i] = s.get(i);
else
group3[i] = s.get(i);
}
for(String ss : group1){
if(ss == null)
break;
System.out.println(ss);
}
System.out.println();
for(String ss : group2){
if(ss == null)
continue;
System.out.println(ss);
}
System.out.println();
for(String ss : group3){
if(ss == null)
continue;
System.out.println(ss);
}
}
}
I hope it useful for you.

Related

How to split strings of list into string array

I have a list that contains ("One.two.three", "one.two.four"). I want to save then in a string array as
One
two
three
one
two
four
What is the logic behind it?
You should be using java 8 to run this code. Just take those strings and split them on "."
split method of java need regex so to match "." you need "\.".Then transform array to list, then add words to list.
public static void main(String[] args) {
List<String> words = new ArrayList<String>();
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("one.two.four");
list.stream().forEach(str -> {
words.addAll(Arrays.asList(str.split("\\.")));
});
System.out.println(words.toString());
//output : [One, two, three, one, two, four]
}
For java 8+, you can use flatmap as -
String[] words = list.stream().flatMap(str -> Arrays.stream(str.split("\\."))).toArray(String[]::new);
If you are talking about the static arrays it is important to know array size to avoid "index is out of bounds" exception.
This way, I provide the solution that counts the number of words and then creates output s array to save every word.
We can use the String.split() function to get the single words we adding to output array:
String[] a = {"One.two.three", "one.two.four"};
int count = 0;
for (int i = 0; i < a.length; i++) { //skip this loop if you know the wanted array size
count += a[i].split("\\.").length;
}
String[] s = new String[count];
int k = 0;
for (int i = 0; i < a.length; i++) {
String[] b = a[i].split("\\.");
for (int j = 0; j < b.length; j++) {
s[k++] = b[j];
}
}
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
Try this.
FOR JAVA 1.8+
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
list.forEach(string -> {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
});
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}
UPTO JAVA 1.7
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
for (String string : list) {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
}
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}
If you are below Java 8 you can use this snippet:
public class Main {
public static void main(String[] args) throws Exception {
List<String> originalList = new ArrayList();
List<String> finalList = new ArrayList();
originalList.add("One.two.three");
originalList.add("One.two.four");
for(String myString : originalList) {
//The \\ is to scape the dot
finalList.addAll(Arrays.asList(myString.split("\\.")));
}
//Creates an array from the list
String[] theArray = finalList.toArray(new String[finalList.size()]);
}
}
Finally, theArray will contain:
[One, two, three, one, two, four]
Take a look at the docs about splitting an string into parts

How to add multiple characters to one index in a Char Array?

Im currently trying to create a function where my input is a string such as "AABBCCDDEE" and the function outputs a String array "AA""BB""CC" and so on.
public static char[] stringSplitter(final String input) {
String[] strarray = new String[input.length()];
if (input == null) {
return null;
}
char[] chrarray = input.toCharArray();
char[] outputarray = new char[input.length()];
int j = 0;
for (int i = 0; i < chrarray.length; i++) {
char chr = chrarray[i];
System.out.print(chr);
outputarray[j] = chrarray[i]; //here i need to find a way to add the characters to the index at j if the preceding characters are equal
if (i + 1 < input.length() && chrarray[i + 1] != chr) {
j++;
outputarray[j] = chrarray[i + 1];
System.out.println(" ");
}
}
}
Arrays are fixed-length, so you can't do this with an array unless you allocate one with sufficient extra room up-front (which would require a pass through the string to find out how much extra room you needed).
Instead, consider using a StringBuilder for the output, which you can convert into a char array when you're done.
If I understood correctly, you want to split the characters in a string so that similar-consecutive characters stay together. If that's the case, here is how I would do it:
public static ArrayList<String> splitString(String str) {
ArrayList<String> output = new ArrayList<>();
String combo = "";
//iterates through all the characters in the input
for(char c: str.toCharArray()) {
//check if the current char is equal to the last added char
if(combo.length() > 0 && c != combo.charAt(combo.length() - 1)) {
output.add(combo);
combo = "";
}
combo += c;
}
output.add(combo); //adds the last character
return output;
}
Note that instead of using an array (has a fixed size) to store the output, I used an ArrayList, which has a variable size. Also, note that it's a list of strings (stores strings), not characters. The reason for this is that if it was a list of characters I wouldn't be able to store more than one character in the same index.
In each iteration of the loop, I check for equality between the current character and it's consecutive. The variable combo is used to temporarily store the characters (in a string) before they go to output.
Now, to print the results in a clear way:
public static void main(String[] args)
{
String input = "EEEE BCD DdA";
ArrayList<String> output = splitString(input);
System.out.print("[");
for(int i = 0; i < output.size(); i++) {
System.out.print("\"" + output.get(i) + "\"");
if(i != output.size()-1)
System.out.print(", ");
}
System.out.println("]");
}
The output when running the above code will be:
["EEEE", " ", "B", "C", "D", " ", "D", "d", "A"]
You can use an ArrayList of type String to store the consecutive letter Strings after splitting them. This code should work for you.
import java.util.*;
public class StringSplitter{
static ArrayList<String> splitString(String str)
{
ArrayList<String> result_list= new ArrayList<String>();
int last_index;
if(str == null)
{
return null;
}
else
{
while(str.length() != 0)
{
last_index = str.lastIndexOf(str.charAt(0));
result_list.add(str.substring(0, last_index+1));
str = str.substring(last_index+1);
}
}
return result_list;
}
public static void main(String[] args)
{
ArrayList<String> result = splitString("AABBCCDDEEE");
System.out.println(result);
}
}
I have used an ArrayList because it does not require you to fix a size while declaration.

return List<String> from string that can be split by words and then appended in Java

For instance, if I have the string "Bob Bakes Brownies", is there any way I can get this method to produce a list of three strings: "Bob", "Bob Bakes", and "Bob Bakes Brownies"
Any feed back would be appreciated.
Create a list to return. Loop through the String looking for spaces. For each space that you find, add a substring to the list, that starts at the zero index and goes up to the space (not including the space).
When there are no more spaces, add the entire string to the list, and return.
You can use .split() to get an array of the individual words or use StringTokenizer
Good approach will be split(" ") the string, this will produce an array. Then you can iterate on the array when every time you concatenate the current array cell with StringBuilder or a normal concatenation and print the result on every iteration.
public void listOfStrings(String s){
ArrayList<String> result = new ArrayList<String>();
int p = 0;
for (int i = 0; i < s.length() ; i++) {
if(s.charAt(i) == ' ') {
result.add(p, s.substring(0, i));
p++;
}
if(i == s.length()-1)
result.add(p,s);
}
}
Try this:
static List<String> createStringList(String string) {
String[] parts = string.split(" ");
List<String> result = new ArrayList<>();
StringBuilder currentString = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) {
currentString.append(" ");
}
currentString.append(parts[i]);
result.add(currentString.toString());
}
return result;
}
public ArrayList<String> solution(String s){
ArrayList<String> result = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
String[] array = s.split(" ");
for(String str:array){
sb.append(str);
result.add(sb.toString());
}
return result;
}
String string = "Bob Bakes Brownies";
List<String> list = Arrays.asList(string.split(" "));

Convert lines to different Arrays in Java

I have a .txt file with lines (in my situation 2). I need to read lines and convert each to a different Array. Ex:
1 line - A,B,C
2 line - D,E,F,G, etc.
and convert this to:
[A,B,C]
[D,E,F,G]
I'm doing this with String.split(", ")
ArrayList<String> al_1 = new ArrayList<String>();
ArrayList<String> al_2 = new ArrayList<String>();
while(true){
String[] line = rbuff.readLine().split(",");
for(String i : line){
al_1.add(i);
}
if(line == null) break;
}
What's the best way to fill the second?
Thx.
Maybe you must use
ArrayList<ArrayList<String>> al = new ArrayList<ArrayList<String>>();
instead of
ArrayList<String> al_1 = new ArrayList<String>();
ArrayList<String> al_2 = new ArrayList<String>();
and fullfill this list with al.add()
IMO easier to keep a list of lists.
List<List<String>> lineLists = new ArrayList<List<String>>();
while (true) {
List<String> lineList = new ArrayList<String>();
String[] line = rbuff.readLine().split(",");
for (String i : line) {
lineList.add(i);
}
lineLists.add(lineList);
if (line == null) break;
}
(Ignoring that there are any number of ways to split immediately into an array or list w/o the inner loop. Either way, the inner loop should be refactored.)
This solution will allow you to add a new ArrayList to the myArrayList for each row your read of your file:
List<List<String>> myArrayList = new ArrayList<List<String>>();
List<String> myStrings;
while (true) {
myStrings = new ArrayList<String>();
String[] line = rbuff.readLine().split(",");
for (String i : line) {
myStrings.add(i);
}
myArrayList.add(myStrings);
if (line == null)
break;
}
You will have a List with one List inside for each row of your text file.
MyArrayList
|
|_____List('A', 'B', 'C')
|
|_____List('D', 'E', 'F', 'G')
|
|_____(...)
Well that's pretty much what I'd do, but with the mention that if you don't need your lines to inside ArrayList objects, you can use array Strings (String[]). Here's an example:
private static String s1 = "A,B,C",s2="D,E,F";
private static List<String> lines = new ArrayList<String>(){{add(s1);add(s2);}};
public static void main(String[] args) throws Throwable {
Map<Integer,String[]> linesToArraysMap = new HashMap<Integer,String[]>();
for(int i=1;i<=lines.size();i++) {
linesToArraysMap.put(i, lines.get(i-1).split(","));
//if you want to get them as ArrayLists you can do:
//List<String> lineList = Arrays.asList(lines.get(i-1).split(","));
}
for(String[] stringArr:linesToArraysMap.values()) {
System.out.println(Arrays.toString(stringArr));
}
}

Android array sorting

I have an array ordered in alphabetical order;
[0] = apple
[1] = banana
[2] = mango
[2] = melon
What I need to do now, Is split the string array into smaller string arrays with groups of the letters, so the output would be:
[0] = apple
[0] = banana
[0] = mango
[1] = melon
I've tried a few methods, but all of them are hopeless, Can you give me a piece of code that will do this? I promise to give the best answer a tick and all the good answers a point!
Here's how I would do :
create a sorted map (for example a TreeMap) with the first char as key, and a list of fruits as value
iterate through the original array.
at each iteration, extract the first char and see if the map contains it as a key. If not, create an empty list of fruits, and put it in the map. Put the current fruit in the list (whether it was already in the map or not)
Ask for the values of the map : it's an ordered collection of fruit lists. transforming it into an array of arrays is trivial with Collection.toArray.
Here is a simple but not thoroughly optimized example. Also I'm not sure how this will fare with multi-byte first characters as in Umlauts etc.
public static void sortByFirstChar() {
String[] array = new String[4];
array[0] = "apple";
array[1] = "banana";
array[2] = "mango";
array[3] = "melon";
HashMap<Character, ArrayList<String>> charToList = new HashMap<Character, ArrayList<String>>();
for (String item : array) {
char firstChar = item.charAt(0);
if (charToList.containsKey(firstChar)) {
charToList.get(firstChar).add(item);
} else {
ArrayList<String> list = new ArrayList<String>();
list.add(item);
charToList.put (firstChar, list);
}
}
Set<Character> keySet = charToList.keySet();
for (char key : keySet) {
// Here are the arrays
System.out.println("Items for char " + new Character((char)key).toString() + ":");
for (String item : charToList.get(key)) {
System.out.println (" " + item);
}
}
}
Sample output:
Items for char b:
banana
Items for char a:
apple
Items for char m:
mango
melon
You will definitely want to use a better way to store the data instead of arrays... maybe a TreeMap or just a List of strings:
String[] arr = new String[]{"apple", "banana", "mango", "melon"};
List<List<String>> arrs = new ArrayList<List<String>>();
char f = 0;
List<String> last = null;
for(String s : arr){
if( f != s.charAt(0) ){
f = s.charAt(0);
// since first the char is different, create a new array
last = new ArrayList<String>();
last.add(s);
if( last != null ){
arrs.add(last);
}
}
else {
last.add(s);
}
}
In the case above, you will have a List of Lists of strings (arrs). Good thing about lists is that their size is dynamic (arrays dimensions are static).
Here's an UNOPTIMIZED solution. I tested for a few different combos. The output is list of arrays. The printList function prints the array in logCat you might want to replace it with your own function:
public class SortArray extends Activity {
ArrayList matchedFruits = new ArrayList();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String fruits[] = new String[7];//Sorted array
fruits[0] = "apple";
fruits[1] = "apricot";
fruits[2] = "banana";
fruits[3] = "mango";
fruits[4] = "melon";
fruits[5] = "pineapple";
fruits[6] = "peach";
char currChar=fruits[0].charAt(0);//Get first char of first element
boolean match=false;
int len=fruits.length;
List tmp = new ArrayList();
for(int i=1;i < len;i++)
{
Log.d("Comparing ", fruits[i].charAt(0)+","+currChar);
if (fruits[i].charAt(0)==currChar)
{
if (match==false)//new match?
{
match=true;//Reset search
tmp.clear();//clear existing items
tmp.add(fruits[i-1]);
Log.d("Started new list ", fruits[i-1]);
}
else
{
tmp.add(fruits[i-1]);
Log.d("Added to list ", fruits[i-1]);
}
}
else
{
match=false;
tmp.add(fruits[i-1]);
matchedFruits.add(tmp.toArray(new String[tmp.size()]));//add to final list
Log.d("Finished a list ", fruits[i-1]);
tmp.clear();//clear existing items
}
currChar=fruits[i].charAt(0);
}
tmp.add(fruits[len-1]);
matchedFruits.add(tmp.toArray(new String[tmp.size()]));//add left over items
printList();
}
void printList()
{
//Print the list
for(int i=0;i < matchedFruits.size();i++)
{
String tmp2[]= matchedFruits.get(i);
for (int j=0;j < tmp2.length;j++)
{
Log.d("Final list", "Array #"+i+"["+j+"],"+tmp2[j]);
}
}
}
}

Categories

Resources