All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.vaadin.data.provider.ListDataProvider Maven / Gradle / Ivy

There is a newer version: 8.27.3
Show newest version
/*
 * Copyright (C) 2000-2024 Vaadin Ltd
 *
 * This program is available under Vaadin Commercial License and Service Terms.
 *
 * See  for the full
 * license.
 */
package com.vaadin.data.provider;

import java.util.Collection;
import java.util.Comparator;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;

import com.vaadin.server.SerializableComparator;
import com.vaadin.server.SerializablePredicate;

/**
 * {@link DataProvider} wrapper for {@link Collection}s.
 *
 * @param 
 *            data type
 * @since 8.0
 */
public class ListDataProvider
        extends AbstractDataProvider>
        implements InMemoryDataProvider {

    private SerializableComparator sortOrder = null;

    private SerializablePredicate filter;

    private final Collection backend;

    /**
     * Constructs a new ListDataProvider.
     * 

* No protective copy is made of the list, and changes in the provided * backing Collection will be visible via this data provider. The caller * should copy the list if necessary. * * @param items * the initial data, not null */ public ListDataProvider(Collection items) { Objects.requireNonNull(items, "items cannot be null"); backend = items; sortOrder = null; } /** * Returns the underlying data items. * * @return the underlying data items */ public Collection getItems() { return backend; } @Override public Stream fetch(Query> query) { Stream stream = getFilteredStream(query); Optional> comparing = Stream .of(query.getInMemorySorting(), sortOrder) .filter(c -> c != null) .reduce((c1, c2) -> c1.thenComparing(c2)); if (comparing.isPresent()) { stream = stream.sorted(comparing.get()); } return stream.skip(query.getOffset()).limit(query.getLimit()); } @Override public int size(Query> query) { return (int) getFilteredStream(query).count(); } private Stream getFilteredStream( Query> query) { Stream stream = backend.stream(); // Apply our own filters first so that query filters never see the items // that would already have been filtered out if (filter != null) { stream = stream.filter(filter); } stream = query.getFilter().map(stream::filter).orElse(stream); return stream; } @Override public SerializableComparator getSortComparator() { return sortOrder; } @Override public void setSortComparator(SerializableComparator comparator) { this.sortOrder = comparator; refreshAll(); } @Override public SerializablePredicate getFilter() { return filter; } @Override public void setFilter(SerializablePredicate filter) { this.filter = filter; refreshAll(); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy