2017-05-15 5 views
0

私は自分のデータのためのカスタムクラスPersonを定義し、次のようにgroupByKey操作を使用:カスタムクラスでgroupByKeyを使用すると、グループが正しく表示されないのはなぜですか?

public class Person implements Serializable { 
    private static final long serialVersionUID = 1L; 
    private int personId; 
    private String name; 
    private String address; 
    public Person(int personId, String name, String address) { 
     this.personId = personId; 
     this.name = name; 
     this.address = address; 
    } 
    public int getPersonId() { return personId;} 
    public void setPersonId(int personId) { this.personId = personId;} 
    public String getName() { return name;} 
    public void setName(String name) { this.name = name;} 
    public String getAddress() { return address;} 
    public void setAddress(String address) { this.address = address;} 
} 
List<Person> personList = new ArrayList<Person>(); 
personList.add(new Person(111, "abc", "test1")); 
personList.add(new Person(222, "def", "test2")); 
personList.add(new Person(333, "fhg", "test3")); 
personList.add(new Person(111, "jkl", "test4")); 
personList.add(new Person(555, "mno", "test5")); 
personList.add(new Person(444, "pqr", "test6")); 
personList.add(new Person(111, "xyz", "test7")); 

JavaRDD<Person> initialRDD = sc.parallelize(personList, 4); 

JavaPairRDD<Person, Iterable<Person>> groupedBy = 
    initialRDD.cartesian(initialRDD).groupByKey(); 

が、次を使用して、このキーに基づいて任意のグループ化を行わないため、結果を。

groupedBy.foreach(x -> System.out.println(x._1.getPersonId())); 

結果は次のとおりです。222 111 555 444 555 111 222 111 333 222 444 111 111 111 444 111 333 111 111 222 555 111 333 333 444 111 111 555

私は唯一のユニークなキーであることを、結果の意志を期待しています。 SparkのgroupByKey機能で私の理解が間違っていますか?

答えて

1

groupByKeyは、hashCodeequalsの意味のある実装に依存します。独自の実装を提供していないため、Personはデフォルトのものを使用しますが、このシナリオでは役に立たないものです。

例えば試してみてください。

@Override 
public int hashCode() { 
    return this.personId; 
} 

@Override 
public boolean equals(Object o) { 
    return this.hashCode() == o.hashCode(); 
} 
関連する問題