List of List in for loops Java - java

I have problem. I try to do develop
Program ask me for some numbers a few times. I give list of numbers. I try to save them in List>. Numbers can be split by space. Now I have this code :
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TimeSeries {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Numbers of rows:");
Scanner in = new Scanner(System.in);
int NumberLines = in.nextInt();
in.nextLine();
String Ciag;
List<List<Integer>> ll = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < NumberLines; i++) {
list.clear();
System.out.println("Add row " +(i+1));
Ciag = in.nextLine();
for (int t=0; t<Ciag.length(); t++) {
if(Character.isWhitespace(Ciag.charAt(t)))
{
}
else
{list.add(Character.getNumericValue(Ciag.charAt(t)));
}
}
System.out.println(list);
ll.add(list);
}
System.out.println(ll);
}
}
But my output is (example) :
Numbers of rows:
3
Add row 1
0 0 0
[0, 0, 0]
Add row 2
1 2 3
[1, 2, 3]
Add row 3
54 6 8
[5, 4, 6, 8]
[[5, 4, 6, 8], [5, 4, 6, 8], [5, 4, 6, 8]]
But I need to have [[0,0, 0], [1, 2, 3], [5, 4, 6, 8]]

The problem is that you add the same list into ll multiple times.
You need to add different lists to get the behavior you want.
For that, you need to create a fresh new list in each iteration of the for loop, instead of clearing and reusing the existing list.
Change these lines:
List<List<Integer>> ll = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < NumberLines; i++) {
list.clear();
To this:
List<List<Integer>> ll = new ArrayList<>();
for (int i = 0; i < NumberLines; i++) {
List<Integer> list = new ArrayList<>();

Related

Is there a way to subtract an array from an array?

I have two arrays:
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = [2, 4, 6, 8, 10]
How is it possible to make the output look like this?
list3 = [1, 3, 5, 7, 9]
list3[i] = list1[i] - list2[i];
Unfortunately this does not work for me because the two arrays are not same length.
import java.util.Arrays;
import java.util.Scanner;
public class Infinity {
public static int[] InitialiseStudents(int[] students) {
for (int i = 0; i<students.length; i++){
students[i] = i+1;
}
return students;
}
public static int[] AssignJobs (int[] NumberStudents) {
int StudCount = NumberStudents.length;
int[] Array = NumberStudents;
//loop for every day(t), starting at the second day
for (int t = 2; t <= StudCount; t++) {
System.out.println("Tag" + t);
int[] copy = new int[5];
for (int i = t-1, j=0; j < 5; i+=t) {
copy[j++] = Array[i];
}
System.out.println("-------------");
System.out.println(Arrays.toString(copy));
System.out.println("_________");
break;
}
return Array;
}
public static void main( String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Number of Students: ");
//int n = scan.nextInt();
int n = 10;
int[] students = new int[n];
InitialiseStudents(students);
students = AssignJobs(students);
System.out.println(Arrays.toString(students));
}
}
To make to task VERY clear I just show you everything I have done and the context. This is my homework which I am curently working. The task is...
Initially, a numbering 1, 2, 3, 4, . . . of the students is determined. Then it will be that
every second (start counting with the first student) becomes Garbage officer (these are
the students with the numbers 2, 4, 6, 8, . . . ), from the rest (students 1, 3,
5, 7, . . . ) every third person becomes a refrigerator representative (these are students 5, 11, 17,
23, . . . ), of the rest (students 1, 3, 7, 9, . . . ) every fourth . . . , from which then
we can think of something for each k-th and from the rest for
every (k+1)-th etc. Apparently, some of the residents (students 1, 3, 7)
omitted during distribution and do not have to complete any of the tasks that arise.
Numbers of these students are called Omitted Numbers.
Program an application OmittedNumbers that exactly the Omitted Numbers
an area 1; : : : ;N retrieves and prints, where N is passed on the command line
will. Only use methods that are iterative.
Solution # 1
Convert your arrays to list
List<Integer> list1 = Arrays.asList(array1);
List<Integer> list2 = Arrays.asList(array2);
For List, you can use removeAll function
list1.removeAll(list2);
System.out.println(list1)
Solution # 2
Traverse through each index and remove items if same as follow
int[] array1 = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] array2 = new int[]{2, 4, 6, 8, 10};
List<Integer> result = new ArrayList<>();
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
result.add(array1[i]);
}
}
}
// convert list to array (if needed)
Integer[] resultArray = result.toArray(new Integer[0]);
Here's a simple implementation:
import java.util.ArrayList;
import java.util.List;
record ChoiceResult(List<Integer> chosen, List<Integer> remainder) {}
public class Choose {
static ChoiceResult choose(int interval, List<Integer> candidates) {
List<Integer> chosen = new ArrayList<>();
List<Integer> remainder = new ArrayList<>();
for (int i = 0; i < candidates.size(); i++) {
if ((i+1) % interval == 0) {
chosen.add(candidates.get(i));
} else {
remainder.add(candidates.get(i));
}
}
return new ChoiceResult(chosen, remainder);
}
public static void main(String[] args) {
List<Integer> students = List.of(1,2,3,4,5,6,7,8,9,10);
ChoiceResult garbage = choose(2, students);
ChoiceResult fridge = choose(3, garbage.remainder());
System.out.println("Garbage: " + garbage.chosen());
System.out.println("Fridge: " + fridge.chosen());
}
}
It has the feature of working with an immutable List for the input to the function.
You can use double-layer for loop filtering,The following is just a sample code, you need to think about the details(For example, how to improve the efficiency of calculation, because the efficiency of double-layer for loop is very low).
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] arr2 = {2, 4, 6, 8, 10};
List<Integer> rt = new ArrayList<>();
for (int i = 0; i < arr1.length; i++) {
boolean flag = false;
for (int j = 0; j < arr2.length; j++) {
if(arr1[i] == arr2[j]) {
flag = true;
break;
}
}
if (flag == false) {
rt.add(arr1[i]);
}
}
System.out.println(rt);
Integer[] finalArr = rt.toArray(new Integer[rt.size()]);
for (int i = 0; i < finalArr.length; i++) {
System.out.println(finalArr[i]);
}
}
Collection framework supports union/intersection at base level and just utilize it.
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
List<Integer> list2 = new ArrayList<>(List.of(2, 4, 6, 8, 10));
list1.removeAll(list2);
System.out.println(list1);
}
}
Using Stream API:
import java.util.List;
import java.util.stream.Collectors;
public class StreamTest {
public static void main(String[] args) {
List<Integer> list1 = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> list2 = List.of(2, 4, 6, 8, 10);
List<Integer> list3 = list1.stream()
.filter(i -> !list2.contains(i))
.collect(Collectors.toList());
System.out.println(list3);
}
}
collection methods reference

Reverse subset of ArrayList using multidimensional ArrayList in Java

I am trying to reverse a sublist in a List using the indices provided in a multidimensional List.
I don't have much experience using multidimensional lists/arrays. I don't understand why this doesn't work.
/*
Given a List<Integer> list and List<List<Integer>> operations
reverse the sublist and print out the list after all the operations have been done.
Ex: [5, 3, 2, 1, 3]
[[0,1], [1, 3]]
*/
import java.util.*;
public class ReverseParameters {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(5, 3, 2, 1, 3);
List<List<Integer>> operations = new ArrayList<>(2);
for(int i= 0; i < 3; i++){
operations.add(new ArrayList<>());
}
operations.get(0).add(1);
operations.get(1).add(3);
subList(list, operations);
}
public static void subList (List<Integer> list, List<List<Integer>> operations) {
System.out.println(list);
int vertCount = operations.size();
for (int i = 0; i < vertCount; i++) {
int edgeCount = operations.get(i).size();
for (int j = 0; j < edgeCount; j++) {
int startInd = i;
int endInd = operations.get(i).get(j);
int shift = endInd - startInd;
int right = Math.min(i + shift - 1, list.size() - 1);
int temp = 0;
while (startInd < right) {
temp = list.get(startInd);
list.set(startInd, list.get(right));
list.set(right, temp);
startInd+=1;
right-=1;
}
System.out.println();
System.out.printf(" %d %d%n", startInd, endInd);
System.out.println();
}
}
System.out.println(list);
}
}
The output of this code using [[0,1], [1, 3]] as the indecies is:
[5, 2, 3, 1, 3]
but it should be:
[3, 1, 2, 5, 3]
Can someone please help point me in the right direction?
This can be done as simple as this.
public class Main
{
public static void main(String[] args)
{
//Given a List<Integer> list and List<List<Integer>> operations
//reverse the sublist and print out the list after all the operations have been done.
//Ex: [5, 3, 2, 1, 3]
// [[0,1], [1, 3]]
//Target: [3, 1, 2, 5, 3]
//Steps:
// 0 1 2 3 4 (Indices)
//###############
//[5, 3, 2, 1, 3]
//[3, 5, 2, 1, 3] // Swap index of 0 and 1.
//[3, 1, 2, 5, 3] // Swap index of 1 and 3.
List<Integer> list = Arrays.asList(5, 3, 2, 1, 3);
List<List<Integer>> listOfList = new ArrayList<List<Integer>>(2);
listOfList.add(Arrays.asList(0, 1));
listOfList.add(Arrays.asList(1, 3));
for(int i=0; i < listOfList.size(); ++i) {
final int indexA = listOfList.get(i).get(0); //[0 , [1
final int indexB = listOfList.get(i).get(1); // 1], 3]
//Swap the indices.
final int tmpValue = list.get(indexA);
list.set(indexA, list.get(indexB));
list.set(indexB, tmpValue);
}
System.out.println(list);
//[3, 1, 2, 5, 3]
}
}
You are overcomplicating your code with unnecessary variables that makes it difficult to find the problem. Please se a more simple code with explanation:
public static void main(String[] args) {
List<Integer> list = Arrays.asList(5, 3, 2, 1, 3);
List<List<Integer>> operations = new ArrayList<>(2);
// Initialize your operations
operations.add(Arrays.asList(0,1));
operations.add(Arrays.asList(1,3));
subList(list, operations);
}
public static void subList (List<Integer> list, List<List<Integer>> operations) {
// You just iterate over the operations
for (List<Integer> operation : operations) {
// For each operation, store left and right indexes.
int left = operation.get(0);
int right = operation.get(1);
// Iterate until both indexes find each other
while (left < right) {
// Swap left and right elements in input list
int aux = list.get(left);
list.set(left, list.get(right));
list.set(right, aux);
// Now you move your indexes
++left;
--right;
}
}
System.out.println(list);
}
Please note that, depending on what the question asks, you may also need to verify if the operations indexes are within the list boundaries so you won't end up getting an ArrayIndexOutOfBoundsException. So be always careful with edge cases.
You can get subset by List.subList() , and reverse by Collections.reverse().
static void reverseSubsets(List<Integer> list, List<List<Integer>> subsets) {
for (List<Integer> subset : subsets)
Collections.reverse(list.subList(subset.get(0), subset.get(1) + 1));
}
public static void main(String[] args) {
List<Integer> list = Arrays.asList(5, 3, 2, 1, 3);
List<List<Integer>> subsets = List.of(List.of(0, 1), List.of(1, 3));
reverseSubsets(list, subsets);
System.out.println(list);
}
output:
[3, 1, 2, 5, 3]
Note:
toIndex in List.subList(int fromIndex, int toIndex) is exclusive high endpoint of the subList. So you must add 1 to subset.get(1).

How can I change the size of a 2D array?

How would I change the size of a 2d array without rearranging the numbers in an array mainly using for loops and only built in methods?
For example, {{4,5,6,7,10}, {8,4,3,9,13}} to become {{4}, {5,6}, {7,10,8}, {4,3,9,13}}.
I tried making the 2d array into two separate parts then adding it back to a new 2d array. I'm not sure how I would create the second 2d array.
There are many ways to do this. Here is one that works for any triangular number
of elements that originate in a 2D array.
First, flatten them all into a single array.
int[] oneD = Arrays.stream(src).flatMapToInt(Arrays::stream).toArray();
Then reversing the length which should be k where k = n(n+1)/2 the
number of rows would be the following. And the 2D result is partially allocated.
int rows = (int)(Math.sqrt(2*oneD.length + .25) -.5);
int[][] dest = new int[rows][];
Now it's just a matter of copying from the oneD array to the destination.
for (int i = 0, s = 0, e = 1; i < rows; i++) {
dest[i] = Arrays.copyOfRange(oneD, s, e );
s = e;
e += i+2;
}
for (int[] arr : dest) {
System.out.println(Arrays.toString(arr));
}
Prints
[4]
[5, 6]
[7, 10, 8]
[4, 3, 9, 13]
If I understood your question, I recommend you use List<List<Integer>>, for example ArrayList, insted of pure arrays, and you can set your aggregations like this:
List<List<Integer>> matrix = new ArrayList<>();
List<Integer> values = new ArrayList<>();
// add {4,5,6,7,10} to array, result = {{4,5,6,7,10}}
values = new ArrayList<>(Arrays.asList(4,5,6,7,10));
matrix.add(values);
// add {8,4,3,9,13} to last array, result = {{4,5,6,7,10}, {8,4,3,9,13}}
values = new ArrayList<>(Arrays.asList(8,4,3,9,13));
matrix.add(values);
System.out.println("start="+ matrix);
// reset array or you can use another array to copy
matrix = new ArrayList<>();
values = new ArrayList<>(Arrays.asList(4));
matrix.add(values);
values = new ArrayList<>(Arrays.asList(5,6));
matrix.add(values);
values = new ArrayList<>(Arrays.asList(7,10,8));
matrix.add(values);
values = new ArrayList<>(Arrays.asList(4,3,9,13));
matrix.add(values);
System.out.println("end="+ matrix);
Output:
start=[[4, 5, 6, 7, 10], [8, 4, 3, 9, 13]]
end=[[4], [5, 6], [7, 10, 8], [4, 3, 9, 13]]
A possible not-recommended solution
Flatten the 2d array
Collect with grouping on summation sequence
It might be improved to use single atomic counter (i am unable to think)
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class ArrayResize {
public static void main(String[] args) {
Integer[][] input = new Integer[][] {{10, 11, 12 ,13, 14}, {15, 16, 17, 18, 19}};
AtomicInteger index = new AtomicInteger(0);
AtomicInteger group = new AtomicInteger(1);
Collection<List<Integer>> out = Arrays.stream(input)
.flatMap(i -> Arrays.stream(i)) // flatten
.collect(Collectors.groupingBy(i -> {
final int currentIndex = index.getAndIncrement();
return (group.get() * (group.get() + 1)) / 2 == currentIndex
? group.incrementAndGet() // increment group if index matches the summation of the range
: group.get(); // return the group
}))
.values();
System.out.println(out);
}
}
output has to be any Integer array
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class ArrayResize {
public static void main(String[] args) {
Integer[][] input = new Integer[][] {{10, 11, 12 ,13, 14}, {15, 16, 17, 18, 19}};
AtomicInteger index = new AtomicInteger(0);
AtomicInteger group = new AtomicInteger(1);
Integer[][] output = Arrays.stream(input)
.flatMap(i -> Arrays.stream(i)) // flatten
.collect(Collectors.groupingBy(i -> {
final int currentIndex = index.getAndIncrement();
return (group.get() * (group.get() + 1)) / 2 == currentIndex
? group.incrementAndGet() // increment group if index matches the summation of the range
: group.get(); // return the group
})).values().stream() // stream collection
.map(subgroup -> subgroup.toArray(new Integer[0])) // map subgroups to arrays
.collect(Collectors.toList()) // collect as list of arrays
.toArray(new Integer[0][0]); // convert to array
System.out.println(Arrays.deepToString(output));
}
}
Disclaimer
I would not write the above code in any of my production systems
At the current state, it will fail with parallel stream usage
Solution using index count
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ArrayResize {
public static void main(String[] args) {
Integer[][] input = new Integer[][] {{10, 11, 12 ,13, 14}, {15, 16, 17, 18, 19}};
List<Integer> flattened = Arrays.stream(input).flatMap(i -> Arrays.stream(i)).collect(Collectors.toList());
List<Integer[]> temporary = new ArrayList<>();
final int count = flattened.size();
int start = 0;
int range = 1;
while (start < count) {
temporary.add(flattened.subList(start, Math.min(start + range, count)).toArray(new Integer[0]));
start += range;
range++;
}
Integer[][] result = temporary.toArray(new Integer[0][0]);
System.out.println(Arrays.deepToString(result));
}
}
Here's one way to do it, using pure Java code (e.g. loops) and no methods at all.
static int[][] toTriangle(int[][] input) {
// Count number of values
int valueCount = 0;
for (int[] inputRow : input)
valueCount += inputRow.length;
if (valueCount == 0)
return new int[0][0];
// Determine number of result rows, and how many values that can store
int resultRowCount = 0, resultCount = 0;
for (int row = 0; resultCount < valueCount; row++) {
resultRowCount++;
resultCount += row + 1;
}
int oversize = resultCount - valueCount;
// Build result jagged array (last row is likely truncated)
int[][] result = new int[resultRowCount][];
for (int row = 0; row < resultRowCount - 1; row++)
result[row] = new int[row + 1];
result[resultRowCount - 1] = new int[resultRowCount - oversize];
// Copy values
int inputRow = 0, inputCol = 0;
for (int[] resultRow : result) {
for (int i = 0; i < resultRow.length; i++) {
while (inputCol == input[inputRow].length) {
inputRow++;
inputCol = 0;
}
resultRow[i] = input[inputRow][inputCol++];
}
}
return result;
}
Tests
test(new int[][] {{4,5,6,7,10}, {8,4,3,9,13}});
test(new int[][] {{1,2,3,4}, {}, {5,6,7}});
static void test(int[][] input) {
print("Input", input);
print("Result", toTriangle(input));
}
static void print(String label, int[][] arr) {
System.out.println(label + ":");
for (int[] row : arr) {
System.out.print(" [");
String sep = "";
for (int val : row) {
System.out.print(sep + val);
sep = ", ";
}
System.out.println("]");
}
}
Outputs
Input:
[4, 5, 6, 7, 10]
[8, 4, 3, 9, 13]
Result:
[4]
[5, 6]
[7, 10, 8]
[4, 3, 9, 13]
Input:
[1, 2, 3, 4]
[]
[5, 6, 7]
Result:
[1]
[2, 3]
[4, 5, 6]
[7]
Notice how the last row is truncated in length, since there are not enough values to fill a triangle. The second example also shows that it can handle empty sub-arrays in the input.

How do you split an Array List into sublists everytime there is a duplicate value in the Array List

I have the following array list which contains the following
point ids (1,2,3,4,1,8,5,6,8,9,7,9). I am using Java 7
I was wondering how it could be split into sublists i.e the sublists below
(1,2,3,4,1)
(8,5,6,8)
(9,7,9)
I have had problems trying to use a loop within a loop (i.e check each point
from the outer loop with each of the other points in the inner loop) to get
index positions (starPosIndex and endPosIndex) where there are duplicate point ids and ArrayList.sublist(startPosIndex,endPosIndex) to get the correct sublist
int startPos = 0;
int endPos = 0;
for (int j = 0; j < polygonList3.size(); j++){
Point pointToCheck = polygonList3.get(j);
for (int k = 1; k < polygonList3.size(); k++){
Point pointToCheck2 = polygonList3.get(k);
if (pointToCheck.getID() == pointToCheck2.getID()){
startPos = startPos + endPos;
endPos = endPos + k;
//startPos = startPos + endPos;
//for (int startPos = j; startPos < polygonList3.size(); startPos = (startPos) + endPos) {
//endPos = Math.min(startPos + endPos, polygonList3.size());
finalPolygonLists.add(new ArrayList<Point>(polygonList3.subList(startPos, endPos)));//originalPtsSublist2);
//}
}
}
I would solve it in the following manner:
Allocate a HashSet to contain unique values encountered
Allocate a new list for the first sublist
Iterate over the whole list, adding each value to the set. When we encounter a value that is already in the set, we are done with the first sublist, so clear the set, and allocate a new sublist
After iteration, you will have your list of sublists, obtained in O(n) runtime
You can walk along the list, and create slices of the list (using List#subList) as you go. This can be done efficiently, by always checking whether the first element of the current segment of the list appears somewhere else in the list. If it does, you can store this "slice", and continue with the "tail" of the list. If it doesn't, you are finished (and the tail of the list may or may not be part of the result - that's up to you)
Implemented here as an example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListSlicing
{
public static void main(String[] args)
{
runTest(1,2,3,4,1,8,5,6,8,9,7,9);
runTest(1,2,3,4);
runTest(1,1,1,1);
runTest(1,2,1,2,1,2,1,2,1,2,1,2);
runTest();
}
private static void runTest(Integer ... numbers)
{
List<Integer> list = Arrays.asList(numbers);
System.out.println("Input: "+list);
System.out.println("Output: "+slices(list));
}
private static <T> List<List<T>> slices(List<T> input)
{
List<List<T>> slices = new ArrayList<List<T>>();
List<T> current = input;
while (current.size() > 0)
{
T first = current.get(0);
int appearance = current.subList(1, current.size()).indexOf(first);
if (appearance == -1)
{
slices.add(current);
return slices;
}
List<T> slice = current.subList(0, appearance+2);
slices.add(slice);
current = current.subList(appearance+2, current.size());
}
return slices;
}
}
The output is
Input: [1, 2, 3, 4, 1, 8, 5, 6, 8, 9, 7, 9]
Output: [[1, 2, 3, 4, 1], [8, 5, 6, 8], [9, 7, 9]]
Input: [1, 2, 3, 4]
Output: [[1, 2, 3, 4]]
Input: [1, 1, 1, 1]
Output: [[1, 1], [1, 1]]
Input: [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
Output: [[1, 2, 1], [2, 1, 2], [1, 2, 1], [2, 1, 2]]
Input: []
Output: []
The following code tracks the last position for each number and as soon as it founds a duplicate, it will create the sublist and clears all previously tracked entries.
List<Integer> list = Arrays.asList( 1,2,3,4,1,8,5,6,8,9,7,9);
List<List<Integer>> sublists = new ArrayList<>();
Map<Integer,Integer> lastPos = new HashMap<>();
for(int i = 0; i < list.size(); i++) {
Integer current = list.get(i);
if(lastPos.containsKey(current)){
sublists.add(list.subList(lastPos.get(current), i+1));
lastPos.clear();
} else {
lastPos.put(current, i);
}
}
System.out.println(sublists);

Java program to group consecutive number from given numbers in a list<list>

Suppose you are given unique numbers like
11,2,7,6,17,13,8,9,3,5,12
The result will be group of numbers list containing sub list i.e.,
[2,3]-[5,6,7,8,9]-[11,12,13]-[17]
I took this approach to solve this below:
int[] a = { 11, 2, 7, 6, 13,17, 8, 9, 3, 5, 12 };
Arrays.sort(a);
List<List<Integer>> ListMain = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if (a[i + 1] == a[i] + 1) {
temp.add(a[i + 1]);
} else {
ListMain.add(temp);
temp.clear();
}
}
Your overall logic is mostly correct. You have a few problems in your execution, though.
You get an array index out of bounds exception because you call a[i+1] when i = a.length. Change the loop condition to a.length - 1.
You need to use a new inner ArrayList each time, otherwise each array will get wiped out. Change temp.clear(); to temp = new ArrayList<>();.
You need to initialize the new list to the first element, not the empty list. Add temp.add(a[0]); at the beginning and temp.add(a[i+1]) when you've detected you need a new sublist.
You need to add the final list at the end, because your condition won't get called at the end of the loop.
Here's the modified program:
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class SubList {
public static void main(String... args) {
int[] a = { 11, 2, 7, 6, 13,17, 8, 9, 3, 5, 12 };
Arrays.sort(a);
List<List<Integer>> ListMain = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
temp.add(a[0]);
for (int i = 0; i < a.length - 1; i++) {
if (a[i + 1] == a[i] + 1) {
temp.add(a[i + 1]);
} else {
ListMain.add(temp);
temp = new ArrayList<>();
temp.add(a[i+1]);
}
}
ListMain.add(temp);
System.out.println(ListMain);
}
}
Output:
[[2, 3], [5, 6, 7, 8, 9], [11, 12, 13], [17]]
Thanks Garis M Suero for your suggestion after which i got answer
int[] a = { 11, 2, 7, 6, 13,17, 8, 9, 3, 5, 12 };
Arrays.sort(a);
List<List<Integer>> listMain = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if ((i + 1<a.length)&&( a[i] + 1==a[i + 1])) {
temp.add(a[i]);
} else {
temp.add(a[i]);
listMain.add(temp);
temp = new ArrayList<>();
}
}
for (List<Integer> lstI : listMain) {
for (Integer i : lstI) {
System.out.println(i);
}
System.out.println("================");
}

Categories