Finding two similar arrays using streams

Let's say I have a list of objects, each of which contains its own array of strings. I need to find objects with a lot of duplicates with a given array. I can simply achieve this using some for loops, if and counters, but I want to do this using Java 8 threads. I really hope this is possible.

@Test
public void test() {

    String mainArray[]  = {"a", "b", "c"};
    List<ElementsList> elems = new ArrayList<>();

    ElementsList a = new ElementsList(new String[]{"d", "e", "a"});
    ElementsList b = new ElementsList(new String[]{"b", "c", "d"});

    elems.add(a);
    elems.add(b);

    List<ElementsList> result = elems.stream()...;

    assertTrue(result.contains(b));
}

private class ElementsList {

    private String elements[];

    private ElementsList(String elements[]) {
        this.elements = elements;
    }

    public String[] getElements() {
        return elements;
    }
}
+4
source share
3 answers

I can think of this, for example:

List<String> main = Arrays.asList(mainArray);
Stream.of(a, b)
            .map(x -> new AbstractMap.SimpleEntry<>(x, new ArrayList<>(new ArrayList<>(Arrays.asList(x.elements)))))
            .map(entry -> {
                entry.getValue().removeAll(main);
                entry.setValue(entry.getValue());
                return entry;
            })
            .sorted(Comparator.comparing(e -> e.getValue().size()))
            .map(Entry::getKey)
            .forEach(el -> System.out.println(Arrays.toString(el.elements)));

Essentially, all of the elements in the mutable Listand make removeAllout mainArrayand sort results based on the size of the others.

+4
source

Here is a simple approach:

import static java.util.Comparator.comparingLong;

Set<String> mainSet = new HashSet<>(Arrays.asList(mainArray));

ToLongFunction<ElementsList> countMatches = el -> 
        Arrays.stream(el.getElements())
            .filter(mainSet::contains)
            .count();

ElementsList result = elems.stream()
        .max(comparingLong(countMatches))
        .get(); // or throw if elems is empty
+1

, .

List<String> main = Arrays.asList(mainArray);
    Stream.of(a, c, b)
            .map(x -> new AbstractMap.SimpleEntry<>(x, new ArrayList<>(main)))
            .peek(entry -> {
                entry.getValue().removeAll(Arrays.asList(entry.getKey().elements));
                entry.setValue(entry.getValue());
            })
            .sorted(Comparator.comparing(e -> e.getValue().size()))
            .map(Map.Entry::getKey)
            .forEach(el -> System.out.println(Arrays.toString(el.elements)));
0

Source: https://habr.com/ru/post/1685081/


All Articles