Java Program – Pick the Element by interval from the List


This program helps to retrieve a list of the objects from another list of objects based on initial index value and Interval. This is a very common requirement when a developer wants to generate the sample report from a big data set. The developer should give equal opportunity to pick the records from the big data set and they iterate the big data set based on interval value.
In this case Sample case generated from the entire universe as it will traverse the records based on interval till the end of the record.
Please find the sample code written in Java below, please go through and provide your feedback. There are multiple ways to solve a problem and we selected the easier one so everyone can understand.

Java Code

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

 * This class helps to retrieve List of object from List based on Initial Index
 * and uniform Interval.
 * @author dknitk
public class ReadFileAndPickRecByIndex {

	 * This is the main method which helps to start the program execution.
	 * @param args
	public static void main(String[] args) {

		// File Location
		String path = "E:/FileLocation/Data/";
		// File Name
		String fileName = "Generate_Sample.txt";
		// Call method to print the result
		printTheResult(path, fileName, 1, 188);


	 * This method helps to retrieve and print the result.
	 * @param path
	 * @param fileName
	 * @param initalIndex
	 * @param interval
	private static void printTheResult(String path, String fileName, int initalIndex, int interval) {
		// Full File Location
		String fileWithPath = path + fileName;
		// Call method to read number from text file and generate List
		List<Long> listCaseUniverse = readDataFromFile(fileWithPath);

		System.out.println("*********** Print Result for fileName: " + fileName + " ***************");
		while (initalIndex <= listCaseUniverse.size()) {
			// Print the records
			// Increase the index by interval value
			initalIndex = initalIndex + interval;

	 * This method helps to read the records from the test file and construct
	 * List Object.
	 * @param set
	 * @param dublicateData
	 * @param fileWithPath
	 * @return List
	private static List<Long> readDataFromFile(String fileWithPath) {

		File file = new File(fileWithPath);
		String line = null;
		List<Long> list = new ArrayList<Long>();
		try {
			FileReader fileReader = new FileReader(file);

			// Always wrap FileReader in BufferedReader.
			BufferedReader bufferedReader = new BufferedReader(fileReader);

			// Read Files
			while ((line = bufferedReader.readLine()) != null) {
				Long data = new Long(line.trim());
		} catch (Exception e) {
			System.err.println("**** Exception Occured *****" + e.getLocalizedMessage());
		return list;


Big Data List

Please find the Sample Report below –

Sample Result

Leave a Reply

Your email address will not be published. Required fields are marked *