Depending on the environment, you may have to write old code on purpose. I had the opportunity to write code in Java7 that divides the List and executes the process, so I posted it for the first time.
public class Sample {
public static void main(String[] args) {
List<String> sampleList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
int size = 2; //Number of lists to process at one time
for (int i = 0; i < sampleList.size(); i += size) {
List<String> list = new ArrayList<>(
sampleList.subList(i, Math.min(i + size, sampleList.size()))
);
System.out.println(list); //Perform processing here
}
}
}
[aaa, bbb] // sampleList.subList(0, 2)
[ccc, ddd] // sampleList.subList(2, 4)
[eee] // sampleList.subList(4, 5)
subList (int from, int to)
returns a List from from
(included) to to
(not included).
The list to be processed is acquired by increasing the number of divisions of from
and to
by the for statement.
Math.min (int a, int b)
returns the smaller of the two int values.
If the size of the List is not divisible by the number of divisions, then you need to consider to
,
For the last iteration, we put sampleList.size ()
in to
.
The List obtained by subList
shares data with the original value. That is, changing the value of list
will change the value of sampleList
(Example 1).
However, you can change only the subList without changing the original List by making changes after new (Example 2).
public class Sample {
public static void main(String[] args) {
List<String> sampleList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
int size = 2; //Number of lists to process at one time
System.out.println(sampleList); //Before processing
for (int i = 0; i < sampleList.size(); i += size) {
List<String> list = sampleList.subList(i, Math.min(i + size, sampleList.size()));
list.set(0, "zzz"); //Processing execution
System.out.println(list);
}
System.out.println(sampleList); //After treatment
}
}
[aaa, bbb, ccc, ddd, eee] //Before processing
[zzz, bbb]
[zzz, ddd]
[zzz]
[zzz, bbb, zzz, ddd, zzz] //After treatment
As mentioned above, as a result of updating list
, it can be seen that sampleList
has also been updated.
public class Sample {
public static void main(String[] args) {
List<String> sampleList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
int size = 2; //Number of lists to process at one time
System.out.println(sampleList); //Before processing
for (int i = 0; i < sampleList.size(); i += size) {
List<String> list = new ArrayList<>(
sampleList.subList(i, Math.min(i + size, sampleList.size()))
);
list.set(0, "zzz");
System.out.println(list);
}
System.out.println(sampleList); //After treatment
}
}
[aaa, bbb, ccc, ddd, eee] //After treatment
[zzz, bbb]
[zzz, ddd]
[zzz]
[aaa, bbb, ccc, ddd, eee] //After treatment
As mentioned above, you can see that changing list
does not change sampleList
.
Recommended Posts