0

How do I filter a java collection in Android in such a way that my original collection is preserved?

The original collection must remain unchanged, and any changes made to the filtered collection should only affect it and not the original.

Is it possible to achieve this without adding another lib? I have read that apache and guava may make this process easier.

Rohan
  • 593
  • 7
  • 22

1 Answers1

0

As you can see, running the following code (Java 8) doesn't modify the original collection:

    List<Integer> lst = new LinkedList<>();
    lst.add(1);
    lst.add(2);
    lst.add(3);
    lst.add(4);
    lst.add(5);
    lst.stream()
            .filter(x -> (x % 2 == 0))
            .collect(Collectors.toList())
            .forEach(x -> System.out.print(x + " "));

    System.out.println("\n==============");
    System.out.println(Arrays.toString(lst.toArray()));

OUTPUT

2 4 
==============
[1, 2, 3, 4, 5]
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • I need this for the android platform. I've seen an example similar to what you have created though it does not fit my case. @alfasin – Rohan Mar 15 '16 at 05:35
  • How about the Lightweight Stream Api for Android? https://github.com/aNNiMON/Lightweight-Stream-API @Rohan – NMP Mar 15 '16 at 05:50
  • I'm trying to get it to work without adding another dependency. – Rohan Mar 15 '16 at 05:52
  • 1
    @Rohan you don't specify in the question what is *exactly* your case... That said, something that you can always do is create a [*deep-copy*](http://stackoverflow.com/questions/6182565/deep-copy-shallow-copy-clone) of the collection - transform the copy and leave the original intact. – Nir Alfasi Mar 15 '16 at 06:59