2 개의 문자열 배열이 있습니다.
string [] first = {"ajunkbc","ajunkHello","adedbc","abcjunk","add","ad","a","","junk","ajunk","aajunkbb"};
String [] second = {"abc","aHello","adedbc","abcjunk","add","ad","a","","junk","a","aajunkbb"};
내 merge () 메서드의 결과를 first
배열의 각 요소를 second
쉼표로 구분 된 배열 의 각 요소와 연결하고 싶습니다 .
아래는 내 코드입니다.
private static String[] merge(String [] tests, String [] expectations){
List<String> testList = Arrays.asList(tests);
List<String> expectationsList = Arrays.asList(expectations);
List<String> retList = new ArrayList<String>();
for(String test : testList){
for(String val : expectationsList){
retList.add(test+","+val);
break;
}
}
작동하지 않습니다. 내 코드에 어떤 문제가 있습니까?
잘못된 expectationsList
점은 첫 번째 반복 후 루프를 반복하고 루프에서 벗어나는 것입니다.
for(String val : expectationsList){
retList.add(test+","+val);
break; //<--- breaking out of loop after first iteration each time
}
따라서 결과는 항상의 첫 번째 요소를 검색하는 것입니다 expectationsList
.
원하는 것은 두 배열을 반복하는 것이므로 인덱스를 사용해야합니다.
for (int i = 0; i < testList.size(); i++) {
retList.add(testList.get(i)+","+expectationsList.get(i));
}
또한 이는의 크기가의 크기 testList
와 동일 함을 의미합니다 expectationsList
. 그렇지 않은 경우 메서드에서 예외를 throw해야합니다.
입력 배열을 목록으로 변환 할 필요가 없습니다. 그대로 사용할 수 있습니다.
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
String[] result = new String[tests.length];
for (int i = 0; i < tests.length; i++) {
result[i] = tests[i] + "," + expectations[i]);
}
return result;
}
Java 8 솔루션 :
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
return IntStream.range(0, tests.length).mapToObj(i -> tests[i] + "," + expectations[i]).toArray(String[]::new);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다