简体   繁体   中英

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

I have the following class:

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;
    }   
}

And here is my test class:

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"));
    }
}

My method isGoodEnough() check that in first 3 elements the name is not equal to "ccc", but actually I need to check if names are unique.

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

Note that this will traverse maxFailsCount number of elements even if the first two names are equal. If maxFailsCount could be a large value, you may want to go with something like

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM