2016-11-26 5 views
-1

문자열 배열을 ArrayList의 ArrayList로 변환하고 싶습니다. 여기서는 내부 요소 인 ArrayList에 동적 요소 수가 있습니다. 누가 도와 드릴까요? 미리 감사는Arraylist의 ArrayList에 문자열 배열

String[] sentences = {"hello","how are you","i am fine","and you ?","thank you"} 
//Output with number of elements = 2 
["hello","how are you"] 
["i am fine","and you ?"] 
["thank you"] 
//Output with number of elements = 3 
["hello","how are you","i am fine"] 
["and you ?","thank you"] 
+0

diff는 무엇입니까? 요소 수 = 2와 3 사이? – developer

+0

@bibuche 코드를 원하십니까? – WSS

+0

요소 수는 동적이어야합니다. 총 문장 수는 5입니다. 요소 수 = 2 인 경우 2,2,1을 얻습니다. 요소 수 = 3 인 경우 내부 Arraylist의 문자열 수는 3,2입니다. – bibuche

답변

0
public static void main(String[] args) { 
    String[] sentences = {"hello", "how are you", "i am fine", "and you ?", "thank you"}; 
    System.out.println(split(2,sentences)); 
    System.out.println(split(3,sentences)); 
} 

public static List<List<String>> split(int numberOfElements, String[] sentences) { 
    List<List<String>> lists = new ArrayList<List<String>>(); 
    int index = 0; 
    for (String sentence : sentences) { 
     if (index % numberOfElements == 0) { 
      lists.add(new ArrayList<String>()); 
     } 
     lists.get(index/numberOfElements).add(sentences[index]); 
     index++; 
    } 
    return lists; 
} 

출력 :

[[hello, how are you], [i am fine, and you ?], [thank you]] 
[[hello, how are you, i am fine], [and you ?, thank you]] 
+0

대단히 감사합니다! 그것은 내가 원하는 것입니다. 그러나 두 프로그램 중 가장 빠른 프로그램이 무엇인지 궁금합니다. – bibuche

0
public static void main(String[] args) { 
    String[] sentences = { "hello", "how are you", "i am fine", "and you ?", "thank you" }; 

    List<List<String>> convertIntoList = convertIntoList(sentences, 2); 
    System.out.println(convertIntoList); 

    convertIntoList = convertIntoList(sentences, 3); 
    System.out.println(convertIntoList); 
} 


private static List<List<String>> convertIntoList(String[] sentences, int nbElement) { 
    List<List<String>> listOfListTarget = new ArrayList<List<String>>(); 
    int currentIndex = 0; 

    while (currentIndex < sentences.length) { 

    int nextIndex = currentIndex + nbElement; 
    if (nextIndex > sentences.length) { 
     nextIndex = sentences.length; 
    } 
    final String[] copyOfRange = Arrays.copyOfRange(sentences, currentIndex, nextIndex); 
    List<String> subList = new ArrayList<String>(); 
    subList.addAll(Arrays.asList(copyOfRange)); 
    listOfListTarget.add(subList); 
    currentIndex+=nbElement; 
    } 
    return listOfListTarget; 
} 
+0

대단히 감사합니다! 그것은 내가 원하는 것입니다. 그러나 두 프로그램 중 가장 빠른 프로그램이 무엇인지 궁금합니다. – bibuche

0

이는 숙제인가?

문자열의 배열을 가지고 있고, 그 안에 List <>를 만들려고합니다. 각 내부 목록은 최대 x 개의 요소를 포함합니다.

x 개의 요소를 가져와 List에 넣으려면 for 루프를 사용하면됩니다. 그래서 예를 들어

String[] myStringArray = { ... }; 
List<String> myListOfString = new ArrayList<>(); 
for(int i=0; i<x; i++) { 
    myListOfString.add(myStringArray[i]); 
} 

당신은 당신은 위의 루프를 사용하여 다음과 같은 목록을 얻을 것이다이 값

String[] myStringArray = {"a", "b", "c", "d", "e"}; 
x = 2; 

이있는 경우 :

["a", "b"] 

우수함! 그러나 우리는 myStringArray의 모든 내용을 얻어야합니다! 어떻게해야합니까? 그런 다음 첫 번째 단계를 수행하고 배열의 모든 내용을 반복합니다. 우리는 이렇게 할 수 있습니다.

int i=0; 
while(i < myStringArray.length) { 
    System.out.println(myStringArray[i]); 
    i++; 
} 

어떤 출력 :

a 
b 
c 
d 
e 

이 문제가 해결되지 ...하지만 적어도 우리가 모든 일을 반복하는 방법을 알고있다. 다음 단계는 x를 얻는 것입니다. 단순한 데요? 그래서 기본적으로 우리는 내용으로부터 x의리스트를 생성 할 필요가 있습니다. 어쩌면 문제를 해결하기 위해 몇 가지 예를 만든 논리를 사용할 수 있습니다.

// Create list of list of string here 
int i = 0; 
while(i < myStringArray.length) { 
    // Create list of string here 
    for(int j=0; j<x; j++) { 
     // Add myStringArray[j] to list of string here 
    } 
    // Add the list of string to the list of list of string here 
    i++; 
} 

쉬운 권리? 아니요. 다음 목록을 제공합니다 :

["a", "b"] 
["a", "b"] 
["a", "b"] 
["a", "b"] 
["a", "b"] 

왜? 첫 번째 루프에서는 배열에 몇 개가 있는지 반복합니다. 두 번째 루프에서는 요소 0과 1을 목록에 추가합니다. 분명히 작동하지 않을 것입니다. 두 번째 루프는 이전에 추가 된 요소를 추가해서는 안되며 첫 번째 루프는 두 번째 루프가 수행중인 작업을 인식해야합니다. 아마도 int i을 사용하여 두 번째 루프가 시작되어야하는 위치를 나타낼 수 있다고 생각할 수도 있습니다. i 전체 어레이를 통해 반복되므로

int i = 0; 
while(i<myStringArray.length) { 
    while(i<x) { 
     // add myStringArray[i]; 
     i++; 
    } 
    i++; 
} 

불행히도, 기존과 동일한 값을 사용하여,이 경우에만 다음 목록을

["a", "b"] 

을 줄 것이다. 그래서 0에서 length로 갈 때, i의 값이 두 번째 배열에서 사용됩니다. 다시 루프 할 때 i은 1이되므로 두 번째 루프의 시작은 1입니다.

두 번째 루프에 현재있는 위치를 염두에 두면서 별도의 변수를 계산해야합니다.

int i = 0; 
while(i<myStringArray.length) { 
    int count = 0; 
    while(count < x) { 
     // Add myStringArray[count+i] to list of string 
     count++; 
    } 
    // Add to list of list of string 
    i += count + 1; // Need to be aware of how much we have processed 
} 

이것은 우리가 원하는대로 할 것입니다.하지만 불행히도 특정 값에서 문제가 발생할 수 있습니다. x은 10이고 myStringArray은 길이가 2뿐입니다. count + i = 3의 지점에 도달하면 더 이상 인덱스가 존재하지 않으므로 예외가 발생합니다. 두 번째 루프는 또한 얼마나 많은 양이 남아 있는지를 알아야합니다.

마지막으로 우리는

["a", "b"] 
["c", "d"] 
["e"] 

편집을 줄 것이다 다음 코드

int i = 0; 
while(i<myStringArray.length) { 
    int count = 0; 
    while(count < x && count+i < myStringArray.length) { 
     // Add myStringArray[count+i] to list of string 
    } 
    // Add to list of list of string 
    i += count; // Need to be aware of how much we have processed 
} 

을해야합니다 : 다음 시간이 당신이 뭔가를 시도 몇 가지 코드를 넣어보십시오.

관련 문제