In: Computer Science
Java Generic 2D Linked List Problem
How to convert a 1D linked List into multiple linked lists with sequential values together?
//Example 1: [1,1,2,3,3] becomes [[1,1],[2],[3,3]]
//Example 1: [1,1,2,1,1,2,2,2,2] becomes
[[1,1],[2],[1,1],[2,2,2,2]]
//Example 3: [1,2,3,4,5] becomes [[1],[2],[3],[4],[5]]
public <T> List<List<T>> convert2D(List<T> list) {
// Given a 1D, need to combine sequential values together.
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
//Example 1: [1,1,2,3,3] becomes [[1,1],[2],[3,3]]
//Example 1: [1,1,2,1,1,2,2,2,2] becomes [[1,1],[2],[1,1],[2,2,2,2]]
//Example 3: [1,2,3,4,5] becomes [[1],[2],[3],[4],[5]]
public static <T> List<List<T>> convert2D(List<T> list) {
List<List<T>> result = new ArrayList<>();
T prevVal = null;
for(int i=0; i<list.size(); i++) {
T val = list.get(i);
if(i == 0 || val != prevVal) {
result.add(new ArrayList<>());
prevVal = val;
}
result.get(result.size() - 1).add(val);
}
return result;
}
public static void main(String[] args) {
System.out.println(convert2D(new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3))));
System.out.println(convert2D(new ArrayList<>(Arrays.asList(1,1,2,1,1,2,2,2,2))));
System.out.println(convert2D(new ArrayList<>(Arrays.asList(1,2,3,4,5))));
}
}
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.