1

I have two arrayList and I need to compare them, get the values that are uniques and build a new array with them, problem is some of the values are the same but in uppercase so they shouldn't show as unique value. This is my code alredy, works but is to slow

for (i = 0; i < parsedLocal.size(); i++) {
  for (j = 0; j < parsedRemote.size(); j++) {
     if (parsedLocal[i].toUpperCase().equals(parsedRemote[j].toUpperCase())){ 
        parsedLocal.remove(parsedLocal[i])
    }
  }
}

Then I found this solution that is faster but doesn't compare uppercases or lowercases, any idea on how to do that with that method or similar?

parsedLocal.removeAll(parsedRemote);

2 Answers2

2

The following groovy code should compute the difference (note that the returned collection will contain upper-case values):

parsedLocal*.toUpperCase() - parsedRemote*.toUpperCase()

But you can also use a stream-based computation. This has a slightly higher space complexity, but should have linear time complexity:

Set<String> set1 = parsedLocal.stream()
        .map{it.toUpperCase()}
        .collect(Collectors.toSet());
List<String> retained = parsedRemote.stream()
        .filter{!set1.contains(it.toUpperCase())}
        .collect(Collectors.toList());
ernest_k
  • 44,416
  • 5
  • 53
  • 99
1

Using removeIf can be easy in java 8 as follows:

    List<String> parsedLocal = new ArrayList();
    parsedLocal.add("aa");
    parsedLocal.add("bb");
    List<String> parsedRemote = new ArrayList();
    parsedRemote.add("AA");
    List<String> tmpList = new ArrayList<>(parsedLocal);
    for (String s : parsedRemote) {
        tmpList.removeIf((t) -> t.equalsIgnoreCase(s));
    }
    System.out.println(tmpList);

And the output:

[bb]
Hearen
  • 7,420
  • 4
  • 53
  • 63
  • tryed that, getting an error on tmpList.removeIf line startup failed: Script1.groovy: 8: unexpected token: -> @ line 8, column 30. tmpList.removeIf((t) -> t.equalsIgnoreCase(s)); ^ 1 error – Cristian Gonzalez Jul 19 '18 at 07:23
  • lambda not supported? not using java 8? – Hearen Jul 19 '18 at 07:24
  • 2
    @CristianGonzalez You should tag your question with `groovy` if this is not java code. – ernest_k Jul 19 '18 at 07:25
  • @Hearen openjdk version "1.8.0_111" – Cristian Gonzalez Jul 19 '18 at 07:26
  • @CristianGonzalez Would you please locally tested it using terminal run javac and java? – Hearen Jul 19 '18 at 07:27
  • If you are using some IDE, you need to make sure the language level is correct. something like this: https://stackoverflow.com/questions/37787079/intellij-unable-to-use-newer-java-8-classes-error-usage-of-api-documented/51372953#51372953 – Hearen Jul 19 '18 at 07:30
  • 1
    @Hearen The problem is that the code is compiled as groovy code. And surely the version of groovy being used doesn't support the java lambda syntax. – ernest_k Jul 19 '18 at 07:31