How to compare strings of a single array in Java?


Let's say there is an array

String[] names = {"Bill", "Den", "James", "Den", "Loris", "Bill", "Den"};

How can I compare in a for loop (or in another way) are these lines related to each other? My task is precisely to output the names of the rows (array elements) that are repeated and output the number of times each row that occurs in the array.

Here is a concrete example, but something is not quite right here.

static public Map<String, Integer> getDuplicate(ArrayList<Unit> list) {
    Map<String, Integer> dupEl = new HashMap<>();
    int count = 0;

    for (int i = list.size() - 1; i > 0; i--) {
        for (int j = 0; j < i; j++) {
            if (list.get(j).equals(list.get(i))) {
                dupEl.put(list.get(i).toString(), ++count);
            }
        }
    }
    return dupEl;
}

Unit class nothing unusual, test class :

public class Unit {
    private String name;
    private int age;

    public Unit(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Unit unit = (Unit) o;

        if (age != unit.age) return false;
        return name != null ? name.equals(unit.name) : unit.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }

    @Override
    public String toString() {
        return "name='" + name;
    }
}

For that matter, here's the list itself and the challenge methods:

ArrayList<Unit> mylist = new ArrayList<>();

mylist.add(new Unit("Edik", 40));
mylist.add(new Unit("Bill", 35));
mylist.add(new Unit("Grace", 25));
mylist.add(new Unit("Jason", 37));
mylist.add(new Unit("Edik", 40));

/* 1) Найти дубликаты  в списке
 * 2) Вывести название дублируемого объекта
 * 3) Указать количество раз, когда встречается объект в списке.
 * */
getDuplicate(mylist).forEach((k, v) -> System.out.println(k + ": " + v));
Author: Vaagn Akopyan, 2019-09-22

3 answers

I will also offer such a solution with streams

public static Map<Unit,Long> getDuplicate(List<Unit> list) {
    return list.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
 2
Author: Andrew Bystrov, 2019-09-23 08:00:30
static public Map<Unit,Integer> getDuplicate(List<Unit> list) {

    Map<String,Integer> dupEl= new HashMap<>();

    for (Unit unit : list) {
        if (dupEl.get(unit) == null) {
            dupEl.put(unit, 1);
        } else {
            duplEl.put(unit, duplEl.get(unit) + 1)
        }
    }

    return dupEl;
}

Or if Java version 8+

public Map<Unit,Integer> getDuplicate(List<Unit> list) {
    Map<String,Integer> map = new HashMap<>();
    list.forEach(unit -> map.put(unit , map.getOrDefault(unit , 0) + 1));
    return map;
}
 2
Author: ЮрийСПб, 2019-09-22 23:45:25

If it is the map Map<String, Integer> that is needed, then in this case the field age and the methods equals, hashCode and toString are not needed at all, because they are not used.

To assemble duplicate sheet elements into a map, you can use the method stream.collect:

public class Test {
    public static class Unit {
        private final String name;

        public Unit(String name) {
            this.name = name;
        }
    }

    static public Map<String, Integer> getDuplicate(ArrayList<Unit> list) {
        return list.stream()
                // собираем в карту
                // дублирующиеся объекты
                .collect(Collectors.toMap(
                        // ключ - строка,
                        // поле 'name'
                        e -> e.name,
                        // значение - количество
                        e -> 1,
                        // суммируем колличество
                        Integer::sum));
    }

    public static void main(String[] args) {
        ArrayList<Unit> myList = new ArrayList<>();
        myList.add(new Unit("Edik"));
        myList.add(new Unit("Bill"));
        myList.add(new Unit("Grace"));
        myList.add(new Unit("Jason"));
        myList.add(new Unit("Edik"));

        getDuplicate(myList).forEach((k, v) -> System.out.println(k + ": " + v));
    }
}

Output:

Edik: 2
Grace: 1
Bill: 1
Jason: 1
 0
Author: , 2020-12-02 21:18:07