Estou tentando achar um jeito de comparar dois vetores de inteiros com tamanhos diferentes e criar um novo vetor a partir dos elementos diferentes.
Por exemplo:
vetA = {1, 2, 3, 4, 5, 6}
vetB = {1, 2, 4}
Fazendo a comparação o resultado seria
vetC = {3, 5, 6}
Alguma luz para o fim desse túnel?
@giufernandes
Boa tarde campeão.
Coloquei três formas de fazer o que você, existem outros métodos e existem bibliotecas que fazem isso. Acredito que possa te ajudar.
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class ComparingTwoArrays {
/**
* vetA = {1, 2, 3, 4, 5, 6}
* vetB = {1, 2, 4}
* vetC = {3, 5, 6}
*/
public static void main(String[] args) {
ComparingTwoArrays comparingTwoArrays = new ComparingTwoArrays();
int[] vetorA = {1, 2, 3, 4, 5, 6};
int[] vetorB = {1, 2, 4};
System.out.println(Arrays.toString(comparingTwoArrays.comparingOne(vetorA, vetorB)));
System.out.println(Arrays.toString(comparingTwoArrays.comparingTwo(vetorA, vetorB)));
System.out.println(Arrays.toString(comparingTwoArrays.comparingThree(vetorA, vetorB)));
}
public int[] comparingOne(int[] vetorA, int[] vetorB) {
if (vetorA.length != vetorB.length) {
vetorA = vetorA.length > vetorB.length ? vetorA : vetorB;
vetorB = vetorA.length < vetorB.length ? vetorA : vetorB;
}
int count = 0;
int[] vetorC = new int[findNotEqualsCount(vetorA, vetorB)];
for (int i = 0; i < vetorA.length; i++) {
int value = findValue(vetorB, vetorA[i]);
if (value >= 0) vetorC[count++] = value;
}
return vetorC;
}
public Integer[] comparingTwo(int[] vetorA, int[] vetorB) {
Supplier<Stream<Integer>> streamA = () -> IntStream.of(vetorA.length > vetorB.length ? vetorA : vetorB).boxed();
Supplier<Stream<Integer>> streamB = () -> IntStream.of(vetorA.length < vetorB.length ? vetorA : vetorB).boxed();
return streamA.get()
.filter(value -> streamB.get().noneMatch(v -> v.equals(value)))
.toArray(Integer[]::new);
}
public Integer[] comparingThree(int[] vetorA, int[] vetorB) {
return Stream.of(ArrayUtils.toObject(vetorA))
.filter(value -> Stream.of(ArrayUtils.toObject(vetorB)).noneMatch(value::equals))
.toArray(Integer[]::new);
}
public int findValue(int[] vetor, int value) {
for (int i = 0; i < vetor.length; i++) if (!findNotEquals(vetor, value)) return value;
return -1;
}
public int findNotEqualsCount(int[] vetorA, int[] vetorB) {
int quant = 0;
for (int value : vetorA) if (!findNotEquals(vetorB, value)) quant++;
return quant;
}
public boolean findNotEquals(int[] vetor, int value) {
for (int i = 0; i < vetor.length; i++) if (value == vetor[i]) return true;
return false;
}
}
Nesse exemplo eu usei
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>