Angad
Angad

Reputation: 11

Java : Compare previous record with current record in arraylist

I have a sorted array list with 6 elements.The first 5 elements have some value, and the 6th one is empty.

I want to loop through this ArrayList, and compare the first 5 elements of first record, with the same elements in next record. If any one of the element is different, then populate 6th element.

Anyone know an easier and faster approach to do that?

Thanks Angad

Upvotes: 0

Views: 2759

Answers (2)

João Esperancinha
João Esperancinha

Reputation: 1159

Maybe this could be an alternative to think about:

public String[] generateFirstRow(int startingRow) {

    final String[] row1 = rowList.get(startingRow);
    final String[] row2 = rowList.get(startingRow + 1);
    final List<String> list1 = Arrays.stream(row1).collect(toList());
    final List<String> toAdd = Arrays.stream(row2).parallel().sorted().filter(s -> !list1.contains(s)).collect(Collectors.toList());
    if (list1.get(list1.size() - 1) == "") {
        list1.set(list1.size() - 1, toAdd.get(0));
        return list1.toArray(new String[0]);
    }
    return new String[0];

}

Now you can call this per row you have untill the pre-last one.

Upvotes: 0

AkashBhave
AkashBhave

Reputation: 749

First split the all records into many String[], then parse all values in each. After that you can compare the current record with the first one. Here is an example:

public class StringComparison {

ArrayList<String[]> list = new ArrayList<String[]>();

public void comapreStrings() {
    // The list you are comparing everything to
    String[] firstRecord = list.get(0);

    for(int n = 1; n < list.size(); n++) {
        String[] currentRecord = list.get(n);
        for (int i = 0; i < currentRecord.length; i++) {
            String val1 = firstRecord[i];
            String val2 = currentRecord[i];
            if (val1.equals(val2)) {
                // The two strings are the same
            } else {
                // Replace "a value" with whatever you want to fill the 6th element with
                currentRecord[5] = "a value";
            }
        }
    }
}

Upvotes: 1

Related Questions