Get the second same value in the ArrayList<String>

162 views Asked by At

I am trying to add marker New direction to the arrayList mergeArray when I found the second 3 value in the buffer arrayList but I am always getting the first 3 value in the ArrayList. How can I get the second one after Amsterdam?

I appreciate any help.

output:

paris
3
water
ball
money
Amsterdam
3
door

output should looks like this:

paris
3
water
ball
money
New direction
Amsterdam
3
door

Code:

    public static void main(String[] args) {

    ArrayList<String> buffer = new ArrayList<String>();
    ArrayList<String> mergeArray = new ArrayList<String>();

    String route = "3";
    String direction = "paris";
    String start = "Amsterdam";

    buffer.add("paris");
    buffer.add("3");
    buffer.add("water");
    buffer.add("ball");
    buffer.add("money");
    buffer.add("Amsterdam");
    buffer.add("3");
    buffer.add("door");

    for (String line : buffer) {
        if (line.equals(route)) {
            mergeArray.add(line);
            int index = buffer.indexOf(line);
            String prevElement = buffer.get(index - 1);
            if (prevElement == direction) {
                String addElem = buffer.get(index + 1);
                mergeArray.add(addElem);

            } else if (prevElement == start) {
                mergeArray.add("New direction");

            }

        }

    }
    for (String key : mergeArray) {
        System.out.println(key);
    }

}
2

There are 2 answers

0
giorashc On BEST ANSWER

Do not use indexOf as it will always retrieve the index of the first appearance.

Keep an auxiliary index variable and use it in your loop:

int auxIndex = 0;
for (String line : buffer) {
        if (line.equals(route)) {
            mergeArray.add(line);           
            String prevElement = buffer.get(auxIndex - 1);
            if (prevElement.equals(direction)) {
                String addElem = buffer.get(auxIndex + 1);
                mergeArray.add(addElem);

            } else if (prevElement.equals(start)) {
                mergeArray.add("New direction");

            }

        }
        auxIndex++
}

also add safety checks so the index will not under/over-flow

0
Adrian B. On

Try using a clasic for, instead of one that uses Iterable

for (int i=0; i<buffer.size(); i++) {
    String line = buffer.get(i);
    if (line.equals(route)) {
        mergeArray.add(line);           
        String prevElement = buffer.get(i - 1);
        if (prevElement == direction) {
            String addElem = buffer.get(i + 1);
            mergeArray.add(addElem);

        } else if (prevElement == start) {
            mergeArray.add("New direction");

        }

    }
}

Also, consider checking for over/underflow problems. You refer to index-1 and index+1, which will cause trouble if the appearance is on the first or last position.