簡體   English   中英

如何使用Java 8通過某些條件檢查集合中的值是否具有唯一性

[英]How to check values in collection for uniques by some criteria using Java 8

我有以下課程:

public final class InfoWrapper {
    private int count;
    private int itemCode;
    private String name;

    public InfoWrapper() {
    }

    public InfoWrapper(final int count, final int itemCode, final String name) {
        super();
        this.count = count;
        this.itemCode = itemCode;
        this.name = name;
    }

    public int getCount() {
        return count;
    }

    public int getItemCode() {
        return itemCode;
    }

    public String getName() {
        return name;
    }   
}

這是我的測試課:

public class TestClass {

    public static void main(String [] args) {
        Deque<InfoWrapper> list = new  ArrayDeque<InfoWrapper>();
        list.add(new InfoWrapper(3, 111, "aaa"));
        list.add(new InfoWrapper(7, 112, "bbb"));
        list.add(new InfoWrapper(12, 113, "ccc"));
        list.add(new InfoWrapper(6, 113, "ccc"));
        list.add(new InfoWrapper(8, 113, "ccc"));
        list.add(new InfoWrapper(3, 113, "ccc"));

        System.out.println("Is good enought : " + isGoodEnought(list, 3));
    }

    private static boolean isGoodEnought(final Deque<InfoWrapper> list, final int maxFailsCount) {
        return !list.stream().limit(maxFailsCount).skip(1).anyMatch((res) -> res.getName().equals("ccc"));
    }
}

我的方法isGoodEnough()檢查前3個元素的名稱是否等於“ ccc”,但實際上我需要檢查名稱是否唯一。

private static boolean isGoodEnought(Deque<InfoWrapper> list,
                                     int maxFailsCount) {
    return list.stream()
               .limit(maxFailsCount)
               .map(InfoWrapper::getName)
               .distinct()
               .count() == maxFailsCount;
}

請注意,即使前兩個名稱相同,也會遍歷maxFailsCount個元素。 如果maxFailsCount可以是一個較大的值,則可能需要使用類似

private static boolean isGoodEnought(Deque<InfoWrapper> list, int max) {
    Set<String> seenNames = new HashSet<>();
    for (Iterator<InfoWrapper> i = list.iterator(); i.hasNext() && max-- > 0;)
        if (!seenNames.add(i.next().getName()))
            return false;
    return true;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM