2017-10-27 4 views
0

Comparator.comparing(....)を使用して、フィールドでのみ比較するためにJava 8でコンパレータを実装します。カスタムコンパレータはJavaのフィールドのみで作成します。

私が実現したい機能は以下の通りです:

List<DocumentLink> documentList = documentLinkService.getDocumentList(baseInstance); 
     //call of custom comparator for DigitalFileCategory due to compare only by Name 
     documentList = documentList.stream() 
       .filter(doc -> category.comp(doc.getDigitalFileCategory())) 
       .collect(Collectors.toList()); 

だから私は、ブール値を返さなければなりません。 DigitalFileCategoryで コンプ方法:

public boolean comp(Object obj) { 
    return super.equals(obj) || 
      (obj != null && 
        getName() != null && 
        getName().equals(((DigitalFileCategory) obj).getName())); 
} 

すべてのアイデア、私はそれをどのように行うことができますか? 私はComparator.comparingを実装しようとするとgetNameを静的にするように求めました。

DigitalFileCategory.class

public class DigitalFileCategory extends _Base { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue(strategy = IDENTITY) 
    @Column(name = "iddigitalfilecategory", nullable = false) 
    private Integer iddigitalfilecategory; 

    @Column(name = "Name", length = 64) 
    private String name; 

    @Column(name = "Priority") 
    private Integer priority; 
    // getter && setter 
} 
+0

'DocumentLink'と' DigitalFileFactory'クラスの基本情報を提供してください。 –

+3

なぜコンパレータが必要ですか? – Oleg

+1

'Comparator'は注文のためのものであり、等価ではありません。 – shmosel

答えて

3

あなたはDigitalFileCategoryの外にnameプロパティを取るためにコンパレータ作成します。

Comparator<DigitalFileCategory> categoryNameComparator = 
    Comparator.comparing((DigitalFileCategory arg) -> arg.getName()); 

し、それを使用している間、あなたはその契約を実行する必要があり(0は、このコンパレータに従って等しいエンティティのために返される):

documentList = documentList.stream() 
       .filter(doc -> 0 == categoryNameComparator.compare(category, doc.getDigitalFileCategory())) 
       .collect(Collectors.toList()); 

は、しかし、なぜこのような複雑なソリューション、あなたは、単にシンプルで行うことはできません平等チェック(category & doc.getDigitalFileCategory()を返すことはありません。null)?

documentList = documentList.stream() 
       .filter(doc -> Objects.equals(category.getName(), doc.getDigitalFileCategory().getName())) 
       .collect(Collectors.toList()); 
+0

あなたの答えをありがとうが、問題は私が名前だけで比較する必要があるということです。 – pik4

+1

@pkont 'Object.equals'提案を修正しました。 'doc.getDFC()'と 'category'は決してnullではないと仮定します。 –

関連する問題