이 기사에서는 목록에서 하위 목록을 찾는 방법을 이해할 것입니다. 목록은 요소를 순차적으로 저장하고 액세스할 수 있도록 하는 정렬된 컬렉션입니다. 여기에는 요소를 삽입, 업데이트, 삭제 및 검색하는 인덱스 기반 메서드가 포함되어 있습니다. 중복 요소를 가질 수도 있습니다. 목록의 일부 또는 하위 집합을 하위 목록이라고 합니다.
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
Input list: [101, 102, 103, 104, 105, 106, 107, 108, 109] Start Index: 3 End input: 6
원하는 출력은 -
The Elements from 3 index position to 6 index position are: [104, 105, 106]
알고리즘
Step 1 - START Step 2 - Declare an integer list namely input_list. Step 3 - Define the values. Step 4 - Use the function subList(3,6) to create a sublist between index value 3 and 6. Step 5 - Display the result Step 6 - Stop
예시 1
여기에서 모든 작업을 'main' 기능 아래에 묶습니다.
import java.util.LinkedList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
int index_start=3;
int index_end=6;
List<Integer> input_list= new LinkedList<>();
for (int i=1; i<=9; i++){
input_list.add(i + 100);
}
System.out.println("The list is defined as: "+input_list);
input_list.subList(index_start,index_end);
System.out.println("The Elements from " +index_start + " index position to "+index_end +" index position are: "+input_list.subList(3,6));
}
} 출력
The list is defined as: [101, 102, 103, 104, 105, 106, 107, 108, 109] The Elements from 3 index position to 6 index position are: [104, 105, 106]
예시 2
여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.
import java.util.LinkedList;
import java.util.List;
public class Demo {
static void sublist(List<Integer> input_list, int index_start, int index_end){
input_list.subList(index_start,index_end);
System.out.println("The Elements from " +index_start + " index position to "+index_end +" index position are: "+input_list.subList(3,6));
}
public static void main(String[] args) {
int index_start=3;
int index_end=6;
List<Integer> input_list= new LinkedList<>();
for (int i=1; i<=9; i++){
input_list.add(i + 100);
}
System.out.println("The list is defined as: "+input_list);
sublist(input_list, index_start, index_end);
}
} 출력
The list is defined as: [101, 102, 103, 104, 105, 106, 107, 108, 109] The Elements from 3 index position to 6 index position are: [104, 105, 106]