-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP09.java
More file actions
47 lines (41 loc) · 1.17 KB
/
P09.java
File metadata and controls
47 lines (41 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package lists;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Class for pack list contains repeated elements
* they should be placed in separate sublist.
* <pre>
* pack([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X).
* X = [[a,a,a,a],[b],[c,c],[a,a],[d],[e,e,e,e]]
* </pre>
*/
public final class P09 {
private P09() {
}
/**
* Pack list of repeated elements into sublists.
*
* @param inputList list of repeated items
* @param <T> type of item
* @return list of separated sublist of repeated elements
*/
public static <T> List<List<T>> pack(final List<T> inputList) {
Objects.requireNonNull(inputList, "List must be not null");
if (inputList.isEmpty()) {
return new ArrayList<>();
}
List<List<T>> resultList = new ArrayList<>();
List<T> sublist = new ArrayList<>();
T last = null;
for (T act : inputList) {
if (!act.equals(last)) {
sublist = new ArrayList<>();
resultList.add(sublist);
}
sublist.add(act);
last = act;
}
return resultList;
}
}