如何从Java中的重复对数组中获取唯一的整数对?

时间:2016-06-10 09:09:57

标签: java

输入值为1,2,1,2,5,6,1,2,8,9,5,6,8,9。 输出应采用以下形式:

1,2   5,6    8,9

在2d字符串数组中。我试过这段代码,但它没有用:

for(int u=0;u<=length_mfr/2;u=u+2)
{
    for(int o=1;o<=length_mfr/2;o=o+2)
    {
        if(main_index[u][0]==main_index[u+2][o+2])
    }
}

3 个答案:

答案 0 :(得分:1)

您正在寻找独特的,而不仅仅是唯一的数字。因此,第一步是创建一个表示一对的类。

public class Pair {
    public final int first;
    public final int second;

    public Pair(int a, int b) {
        first = a;
        second = b;
    }

    public boolean equals(Object o) {
        if (! (o instanceof Pair)) return false;
        Pair p = (Pair)o;
        return first == p.first && second == p.second;
    }

    public int hashCode() {
        return first + second << 16;
    }

    public String toString() {
        return "(" + first + "," + second + ")";
    }

    public String[] toStringArr() {
        String[] s = new String[2];
        s[0] = "" + first;
        s[1] = "" + second;
        return s;
    }
}

从那里你可以将你的输入转换成对,根据需要进行处理,然后转回字符串数组。

public static void main(String args[]){
    int[] arr = { 1, 2, 1, 2, 5, 6, 1, 2, 8, 9, 5, 6, 8, 9 };
    Set<Pair> set = new HashSet<>();
    for(int i = 0; i < arr.length-1; i+=2) {
        set.add(new Pair(arr[i], arr[i+1]));
    }

    String[][] arr2 = new String[set.size()][];
    int i = 0;
    for(Pair p : set) {
        arr2[i] = p.toStringArr();
    }

    //Unique pairs now in string array arr2.
}

答案 1 :(得分:0)

如果int[] i有重复项,您可以创建TreeSet并添加数组i的每个元素。 TreeSet会自动删除重复项,并且只会按升序包含唯一元素。

public static void main(String args[])
{
    int[] i = { 1, 2, 1, 2, 5, 6, 1, 2, 8, 9, 5, 6, 8, 9 };
    Set<Integer> set = new TreeSet<>();
    for (int e : i)
    {
        set.add(e);
    }
 // create an ArrayList to store all unique set values 
 //   use Iterator to loop through ArrayList

    ArrayList ar = new ArrayList<>(set);
    Iterator it = ar.iterator();

// create index variable to loop through the str array
    int index = 0;

// create String array str with the size of the set
    String[] str = new String[set.size()];

    while(it.hasNext() && index<set.size()){
        str[index] = it.next().toString();
        index++;
    }      
}

答案 2 :(得分:-1)

我希望这段代码可以帮到你。

public static void main(String[] args) {

    int[] num = { 1, 2, 1, 2, 5, 6, 1, 2, 8, 9, 5, 6, 8, 9 };
    ArrayList<Integer> numDup = new ArrayList<Integer>();
    numDup.add(num[0]);
    for (int i = 0; i < num.length; i++) {
        if (!numDup.contains(num[i])) {
            numDup.add(num[i]);
        }
    }

    for (Integer pVal : numDup) {
        System.out.println(pVal);
    }
}