Array

Insert interval

Pinterest LinkedIn Tumblr

Write a program to display interval between lower range and higher range elements.

Algorithm Explanation

Construct list using an array and pass the array, lower and higher year to the utility function.
Get the index of higher and lower range.
Take sub list from lower range to higher range and display the sub list.

Source Code

package com.dsacode.DataStructre.array;
 
import java.util.ArrayList;
import java.util.List;
 
public class InsertIntervel {
     
     public static void main(String[] args) {
 
            List < Integer > myList = new ArrayList < Integer >();
 
            for (int i = 1980; i < 2000; i++) {
                myList.add(i);
            }
 
            System.out.println("Array of years: " + myList.toString());
             
            System.out.print("Get range from 1988 to 1994: ");
            List < Integer > subList = getRange(myList, 1988, 1994);
 
            for (Integer i : subList) {
                System.out.print(i +" ");
            }
 
        }
 
        public static List < Integer > getRange(List < Integer > fromList, int lowVal, int highVal) {
            int lowValIndex = fromList.indexOf(lowVal);
            int highValIndex = fromList.indexOf(highVal);
            return fromList.subList(lowValIndex, highValIndex + 1);
        }
 
}

Output

Array of years: [1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]
Get range from 1988 to 1994: 1988 1989 1990 1991 1992 1993 1994

Write A Comment