-1

Removing common value from an ArrayList. consider i have one Arraylist as shown below

arrayList1= [U1,U2,U3,.GY,.GY,.GY,U4,.GY,U5,U6,.GY,.GY,.GY]

My result should be

arrayList1= [U1,U2,U3,.GY,.GY,U4,.GY,U5,U6,.GY,.GY]

Could anyone please help me out.

Thanks in Advance

2 Answers2

1

You can try something like this:

public static void main(String[] args) {
    List<String> list = Arrays.asList("U1","U2","U3",".GY",".GY",".GY","U4",".GY","U5","U6",".GY",".GY",".GY");
    System.out.println(removeCommon(list)); // [U1, U2, U3, .GY, .GY, U4, .GY, U5, U6, .GY, .GY]
}

static List<String> removeCommon(List<String> list) {
    List<String> result = new ArrayList<>(list);
    for (int i = 0; i < list.size() - 2; i++) {
        if (list.get(i).equals(list.get(i + 1)) && list.get(i).equals(list.get(i + 2))) {
            result.remove(i);
        }
    }
    return result;
}
-1

You can do that as following:

// arrayList1 is List of Strings
Set<String> s = new LinkedHashSet<>(arrayList1);
Sanjog Shrestha
  • 417
  • 9
  • 16