Showing posts with label split. Show all posts
Showing posts with label split. Show all posts

Tuesday, 2 May 2023

Split the string by given character using indexOf method in Java

Write a method that takes a string and a character as arguments, and split the string by given character using String indexOf method.

 

Signature

public static List<String> split(String data, int ch)

 

we can implement split method using indexOf, substring methods of String class.

 

public int indexOf(int ch, int fromIndex)

Returns the index of the first occurrence of the character in the character sequence represented by this object that is greater than or equal to fromIndex, or -1 if the character does not occur.

 

public String substring(int beginIndex)

Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

 

public String substring(int beginIndex, int endIndex)

Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

 

Definition of split method is given below.

public static List<String> split(String data, int ch) {
	List<String> splits = new ArrayList<>();
	int currentPosition = -1;
	int fromIndex = 0;
	while ((currentPosition = data.indexOf(ch, fromIndex)) != -1) {
		splits.add(data.substring(fromIndex, currentPosition));
		fromIndex = currentPosition + 1;
	}
	splits.add(data.substring(fromIndex));
	return splits;
}

 


Find the below working application.

 

StringSplitDemo.java
package com.sample.app.strings;

import java.util.ArrayList;
import java.util.List;

public class StringSplitDemo {

	public static List<String> split(String data, int ch) {
		List<String> splits = new ArrayList<>();
		int currentPosition = -1;
		int fromIndex = 0;
		while ((currentPosition = data.indexOf(ch, fromIndex)) != -1) {
			splits.add(data.substring(fromIndex, currentPosition));
			fromIndex = currentPosition + 1;
		}
		splits.add(data.substring(fromIndex));
		return splits;
	}

	public static void main(String[] args) {
		String str = "Hello, are you there";

		List<String> splits = split(str, ' ');
		for (String split : splits) {
			System.out.println(split);
		}

	}
}

 

Output

Hello,
are
you
there

 

  

Previous                                                 Next                                                 Home

Friday, 1 May 2020

Split ArrayList to multiple List chunks

Suppose if you have given an array list of size N and chunk size k < N, then divide the list into multiple sub lists where maximum sub list size is k.

For example, as you see above image, list has 15 elements and for the given chunk size 4, all the 15 elements are divided into 4 sub lists.

Following snippet takes a list and return sublists based on chunk size.

public static <T> List<List<T>> chunkedLists(List<T> list, final int chunkSize) {

         if (list == null) {
                  throw new IllegalArgumentException("Input list must not be null");
         }

         if (chunkSize <= 0) {
                  throw new IllegalArgumentException("Chunk Size must be > 0");
         }

         List<List<T>> subLists = new ArrayList<List<T>>();
         final int listSize = list.size();
         for (int i = 0; i < listSize; i += chunkSize) {
                  subLists.add(new ArrayList<T>(list.subList(i, Math.min(listSize, i + chunkSize))));
         }
         return subLists;
}

Find the below working application.

ListUtil.java
package com.sample.app.utils;

import java.util.ArrayList;
import java.util.List;

public class ListUtil {

 public static <T> List<List<T>> chunkedLists(List<T> list, final int chunkSize) {

  if (list == null) {
   throw new IllegalArgumentException("Input list must not be null");
  }

  if (chunkSize <= 0) {
   throw new IllegalArgumentException("Chunk Size must be > 0");
  }

  List<List<T>> subLists = new ArrayList<List<T>>();
  final int listSize = list.size();
  for (int i = 0; i < listSize; i += chunkSize) {
   subLists.add(new ArrayList<T>(list.subList(i, Math.min(listSize, i + chunkSize))));
  }
  return subLists;
 }

}

ListUtilTest.java

package com.sample.app.utils;

import static com.sample.app.utils.ListUtil.chunkedLists;
import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class ListUtilTest {

 @Test(expected = IllegalArgumentException.class)
 public void nullCheck1() {
  chunkedLists(null, 10);
 }

 @Test(expected = IllegalArgumentException.class)
 public void negativeChunkSize() {
  chunkedLists(Arrays.asList(2, 3, 4, 7), -1);
 }

 @Test
 public void chunkTest() {
  List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);

  List<List<Integer>> subLists = chunkedLists(list, 4);

  assertTrue(Arrays.asList(1, 2, 3, 4).equals(subLists.get(0)));
  assertTrue(Arrays.asList(5, 6, 7, 8).equals(subLists.get(1)));
  assertTrue(Arrays.asList(9, 10, 11, 12).equals(subLists.get(2)));
  assertTrue(Arrays.asList(13, 14, 15).equals(subLists.get(3)));

 }
}

You may like

Thursday, 26 March 2020

Regular Expression: Split a string by the pipe symbol

Suppose you have a string with | characters in it. Since | is a regular expression character we need to escape it while splitting the string like below.

String[] tokens = str.split("\\|");

App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {
  String str = "Hello|How|Are|You";
  
  String[] tokens = str.split("\\|");
  
  for(String token : tokens) {
   System.out.println(token);
  }

 }

}

Output
Hello
How
Are
You


Previous                                                    Next                                                    Home