0
public static void main(String[] args) {
    String OptionId = "111, 112, 113, 114, 115";

    List<String> fullList = Arrays.asList(OptionId.split(","));
    List<String> values = new ArrayList<String>();

    System.out.println("fullList: " + fullList.toString());

    List<String> subItems = fullList.subList(0, 3);

    System.out.println("subItems: " + subItems);

    for (String s : fullList) {
        String strs[] = new String[2];

        if (subItems.contains(s) 
               || subItems.contains(strs[0]) 
               || subItems.contains(strs[1])) {
            values.add(s);                      // save the value to a list
        }
    }
    System.out.println("values: " + values);

    fullList.remove(values);

    System.out.println("fullList: " + fullList);

}

As per my knowledge, the final full list should have only [114, 115]. But its not removed the items present in the sublist.

I have also tried the below code. fullList.removeAll(values);

But it throws the below error.

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at java.util.AbstractList$Itr.remove(AbstractList.java:374)
at java.util.AbstractCollection.removeAll(AbstractCollection.java:376)
at com.tesco.rangeplan.client.Test.main(Test.java:32)

I need the output as below:

fullList: [114,  115]
Emraan
  • 143
  • 1
  • 12

2 Answers2

0

Arrays.asList() returns a fixed-size list backed by the specified array.
So the size being fixed you cannot add or remove elements.
Wrap it into a ArrayList to prevent this limitation :

List<String> fullList = new ArrayList<>(Arrays.asList(OptionId.split(",")));

As alternative you could also do :

List<String> fullList = Arrays.stream(OptionId.split(",")).collect(Collectors.toList());

Note that you invoke remove(Object) with as param a List<String>. It will remove nothing as this method allows to remove the element passed to and actually no List is contained in a List of String. Instead of use removeAll(Collection<?>) that accepts a collection as parameter.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • I have modified as suggested above. But still my final output is: fullList: [111, 112, 113, 114, 115] – Emraan Apr 06 '18 at 10:48
  • You invoke remove() with as param a List of String instead of a String. Use rather removeAll(). I updated. – davidxxx Apr 06 '18 at 10:57
0

You specific error UnsupportedOperationException is because you are using Arrays.asList which returns a fixed sized List. You can not add / remove from it. That's why it throws the exception.

Create the ArrayList and add the items to it. By the way the line

String strs[] = new String[2]; and your follow equals checks will always result in false, since there is nothing in it. Also if you split by , you should also trim() it or else you have whitespaces with your current example.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107