计算和写入重复项

时间:2018-12-22 20:17:07

标签: java arrays sorting duplicates

我正在做一些家庭作业,但我有点坚持做家庭作业的第二部分。 作业的第一部分是制作2个数组

  1. 一个将显示所有正数的数组
  2. 一个显示所有负数的数组。

作业的第二部分是计算并写出哪些数字重复,而无需写下它们出现多少次而仅显示哪些数字。而且代码必须适用于任何数组,而不仅仅是示例中的该数组。

谢谢。

data-index

1 个答案:

答案 0 :(得分:1)

这里有您问题的代码,我在其中添加了一些注释,以帮助您理解代码。

import java.util.*;

public class Homework {

    public static void main(String[] args) {
        List<Integer> array = Arrays.asList(12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87);

        List<Integer> positive = new ArrayList<>();
        List<Integer> negative = new ArrayList<>();
        List<Duplicate> duplicates = new ArrayList<>();

        array.forEach(item -> {
            //get the positive and negative numbers
            if (item < 0)
                negative.add(item);
            else
                positive.add(item);

            //get the amount of times that number appeared in the array
            int frequency = Collections.frequency(array, item);
            //check if the number is not already into duplicates array
            if (frequency > 1 && !duplicates.contains(new Duplicate(item))) {
                duplicates.add(new Duplicate(item, frequency));
            }
        });

        //print the result
        positive.forEach(item -> System.out.printf("Positive value %d %n", item));
        negative.forEach(item -> System.out.printf("Negative value %d %n", item));
        duplicates.forEach(item -> System.out.printf("Duplicate value %d amountOfDuplications %d %n",
                item.getNumber(), item.getAmountOfDuplications()));
    }
}

/**
 * This class helps us to store the number and the amountOfDuplications in the same array
 */
class Duplicate {
    private int number;
    private int amountOfDuplications;

    public Duplicate(int number) {
        this.number = number;
    }

    public Duplicate(int number, int amountOfDuplications) {
        this.number = number;
        this.amountOfDuplications = amountOfDuplications;
    }

    public int getNumber() {
        return number;
    }

    public int getAmountOfDuplications() {
        return amountOfDuplications;
    }

    //here in the equals and hashcode I used only the number as a key,
    // because I considered a duplicate two objects with the same "number" field
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Duplicate)) return false;
        Duplicate duplicate = (Duplicate) o;
        return getNumber() == duplicate.getNumber();
    }

    @Override
    public int hashCode() {
        return Objects.hash(getNumber());
    }
}

在这里您将找到与Java文档的一些链接:

Collections.frequency()

array.forEach() and array.contains()

Equals Method

HashCode Method