I have a String
line "PAA...P.....P..XX.B..Q.OBCCQ.ORRRQ.O"
which has 36 characters and I want to distribute them by 6 elements into ArrayList, but I'm not sure how I can do that.
I want inside of ArrayList to look like,
[["PAA..."],["P....."],["P..XX."],["B..QO"],["BCCQ.O"],["RRRQ.O"]]
and each index has a split string by 6.
Thanks!
You can do it like so:
String s = "PAA...P.....P..XX.B..Q.OBCCQ.ORRRQ.O";
List<List<String>> result = Arrays.stream(s.split("(?<=\\G.{6})"))
.map(Arrays::asList).collect(Collectors.toList());
System.out.println(result);
Output:
[[PAA...], [P.....], [P..XX.], [B..Q.O], [BCCQ.O], [RRRQ.O]]
Explanation of the regex at regex101 :
If you just want a list of list of strings that are of length groupSize
. This will work with any groupSize. The last string will be the remainder if the length is not a multiple of groupSize.
I took the time to provide two options since your description didn't seem to match the desired output.
The first, list1, is a list of lists where each list contains a single 6 character string. List2 is a single list of 6 character strings.
List<List<String>> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
int len = str.length();
int groupSize = 6;
for (int i = 0; i < len; i += groupSize) {
// option 1
list1.add(new ArrayList<>(List.of(str.substring(i, (len - i) > groupSize ?
i + groupSize : len))));
// option 2
list2.add(str.substring(i, (len - i) > groupSize ?
i + groupSize : len));
}
System.out.println("list1 = " + list1);
System.out.println("list2 = " + list2);
Prints
list1 = [[PAA...], [P.....], [P..XX.], [B..Q.O], [BCCQ.O], [RRRQ.O]]
list2 = [PAA..., P....., P..XX., B..Q.O, BCCQ.O, RRRQ.O]
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
ArrayList outer = new ArrayList(); // answer
ArrayList inner = new ArrayList();
int groupOf = 6;
for (int i=0; i< str.length(); i ++){
inner.add(str.substring(i,i+1));
if (inner.size() == groupOf){
outer.add(inner);
System.out.println(outer);
inner.clear();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.