Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip 3 elements in a java string array and get next 3 elements

Tags:

java

loops

I want to get strings of an Array separated by 3 elements. For example I need to skip 3 elements 0,1,2 and take the elements of 3,4,5. And repeat. (skip 6,7,8 and get 9,10,11) until the Array ends. How should I do it?

String s1[] = hh.split("\\r?\\n");
System.out.println(s1[3]);

for (int i=0;i<s1.length; i++){

}

Substring Output :


            org.springframework
            spring-jdbc
            1.0-m4

            org.apache.tomcat
            tomcat-jdbc
            7.0.19

            commons-configuration
            commons-configuration
            20030311.152757

            commons-io
            commons-io
            0.1

            org.springframework.security.oauth
            spring-security-oauth2
            2.1.1.RELEASE


like image 695
nascar895 Avatar asked Apr 12 '26 14:04

nascar895


2 Answers

Solution using the modulo operator and a single loop. No risk of IndexOutOfBounds.

for (int i = 0; i < list.length; i++) {
    if (i % 6 > 2) {
        System.out.println(list[i]);
    }
}

You can flip the condition to i % 6 < 3 if you instead want the first 3 of every 6 elements in the array.

EDIT: The following takes your input and puts it in a List<String[]> where each element contain the 3 lines.

import java.nio.file.*;
import java.util.stream.Stream;
import java.util.*;
import java.nio.charset.Charset;

public class Partition2 {
    public static void main(String[] args) {
        String[] input = ...

        try (Stream<String> stream = Arrays.stream(input)) {
            // https://stackoverflow.com/a/34759493/3717691
            String[] array = stream.map(line -> line.trim()).filter(line -> !line.isEmpty()).toArray(String[]::new);

            List<String[]> results = new ArrayList<String[]>();
            String[] tmp = new String[3];
            for (int i = 0; i < array.length; i++) {
                tmp[i % 3] = array[i];
                if (i % 3 == 2) {
                    results.add(tmp);
                    tmp = new String[3];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
like image 86
Jeppe Avatar answered Apr 15 '26 03:04

Jeppe


for(int i=3;i<s1.length;i+=6){
   for(int j=0;j<3;j++){
         s1[i+j]; // here is your element
    }
}

just adjust loops conditions as you might get IndexOutOfBoundsException if arrag size is not divisible by 6

like image 36
Antoniossss Avatar answered Apr 15 '26 03:04

Antoniossss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!