首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >java 7中的Java streams

java 7中的Java streams
EN

Stack Overflow用户
提问于 2015-05-05 22:19:20
回答 3查看 33.5K关注 0票数 28

我的问题可能太宽泛了,答案可能是简单的“不”,但我不得不问。

在Java7中是否有与(Java8) streams*等效的实现?

我熟悉(Java 8) streams,但我的项目要求是使用Java 7。

*不要与inputStreamoutputStream混淆。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-05-05 22:24:55

在官方API中,没有。

Java 7没有更多的公开更新。如果你是一个客户,你可能仍然会得到较小的更新,但这不是(或者不太可能)用于回迁Stream API。

稍微挖掘一下,你可能会发现StreamSupport。我从未测试过它,但显然它的目标是将Stream API移植到Java6/7,如果您想将它与lambda表达式结合使用,也可以使用retrolambda

Functional Java可能会很有趣。它与Stream API的目的并不完全相同,但如果您的目标是过滤/映射等列表/数组,那么它可能适合您的需要。对于example

代码语言:javascript
复制
final List<Integer> b = list(1, 2, 3).map(add.f(-1));
listShow(intShow).println(b); // [0, 1, 2]

最后,您可以查看Scala的Stream API。由于Scala也可以在JVM上运行,因此您可以混合使用代码。也许这并不完全是你想要的,但如果需要的话,值得一试。

票数 26
EN

Stack Overflow用户

发布于 2015-05-05 22:23:19

Google的Guava库包含Java版本5到7的一些函数习惯用法:

https://github.com/google/guava/wiki/FunctionalExplained

此外,您可能还想查看这个库(我直到几分钟前执行Google搜索时才听说过这个库:-)

http://www.functionaljava.org/

票数 9
EN

Stack Overflow用户

发布于 2017-11-14 21:10:39

这里是Java 6+的另一个选择。

接口:

代码语言:javascript
复制
interface TransformRule<In, Out> {
    Out extract(In obj);
}

interface FilterRule<T> {
    boolean apply(T obj);
}

以及类似Java8Stream的集合/地图容器类:

代码语言:javascript
复制
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

class FPMapContainer<KeyType, ValueType> extends FPContainer<Map<KeyType, ValueType>, Map.Entry<KeyType, ValueType>, ValueType> {
    FPMapContainer(Map<KeyType, ValueType> container) {
        super(container);
    }

    @Override
    public <Out> FPMapContainer<KeyType, Out> map(TransformRule<Map.Entry<KeyType, ValueType>, Out> rule) {
        return new FPMapContainer<>(handleContainer(getMapMapRule(rule)));
    }

    @Override
    public FPMapContainer<KeyType, ValueType> filter(FilterRule<Map.Entry<KeyType, ValueType>> rule) {
        return new FPMapContainer<>(handleContainer(getMapFilterRule(rule)));
    }

    @Override
    public FPMapContainer<KeyType, ValueType> concat(Map<KeyType, ValueType> another) {
        HashMap newOne = new HashMap(container);
        newOne.putAll(another);
        return new FPMapContainer<>(newOne);
    }

    @Override
    public FPMapContainer<KeyType, ValueType> concat(FPContainer<Map<KeyType, ValueType>, Map.Entry<KeyType, ValueType>, ValueType> another) {
        return concat(another.get());
    }

    protected <Out> TransformRule<Map<KeyType, ValueType>, Map<KeyType, Out>> getMapMapRule(final TransformRule<Map.Entry<KeyType, ValueType>, Out> rule) {
        return new TransformRule<Map<KeyType, ValueType>, Map<KeyType, Out>>() {
            @Override
            public Map<KeyType, Out> extract(Map<KeyType, ValueType> obj) {
                Map<KeyType, Out> newOne = new HashMap<>();
                for (Map.Entry<KeyType, ValueType> entry : obj.entrySet()) {
                    newOne.put(entry.getKey(), rule.extract(entry));
                }
                return newOne;
            }
        };
    }

    protected TransformRule<Map<KeyType, ValueType>, Map<KeyType, ValueType>> getMapFilterRule(final FilterRule<Map.Entry<KeyType, ValueType>> rule) {
        return new TransformRule<Map<KeyType, ValueType>, Map<KeyType, ValueType>>() {
            @Override
            public Map<KeyType, ValueType> extract(Map<KeyType, ValueType> obj) {
                Map<KeyType, ValueType> newOne = new HashMap<>();
                for (Map.Entry<KeyType, ValueType> entry : obj.entrySet()) {
                    KeyType key = entry.getKey();
                    ValueType value = entry.getValue();
                    boolean isValid = rule.apply(entry);

                    if (isValid) {
                        newOne.put(key, value);
                    }
                }
                return newOne;
            }
        };
    }
}

class FPCollectionContainer<ValueType> extends FPContainer<Collection<ValueType>, ValueType, ValueType> {
    FPCollectionContainer(Collection<ValueType> container) {
        super(container);
    }

    @Override
    public <Out> FPCollectionContainer<Out> map(TransformRule<ValueType, Out> rule) {
        return new FPCollectionContainer<>(handleContainer(getCollectionMapRule(rule)));
    }

    @Override
    public FPCollectionContainer<ValueType> filter(FilterRule<ValueType> rule) {
        return new FPCollectionContainer<>(handleContainer(getCollectionFilterRule(rule)));
    }

    @Override
    public FPCollectionContainer<ValueType> concat(Collection<ValueType> another) {
        ArrayList<ValueType> newOne = new ArrayList<>(container);
        newOne.addAll(another);
        return new FPCollectionContainer<>(newOne);
    }

    @Override
    public FPCollectionContainer<ValueType> concat(FPContainer<Collection<ValueType>, ValueType, ValueType> another) {
        return concat(another.get());
    }

    protected <Out> TransformRule<Collection<ValueType>, Collection<Out>> getCollectionMapRule(final TransformRule<ValueType, Out> rule) {
        return new TransformRule<Collection<ValueType>, Collection<Out>>() {
            @Override
            public Collection<Out> extract(Collection<ValueType> obj) {
                Collection<Out> newOne = new ArrayList<>();
                for (ValueType entry : obj) {
                    newOne.add(rule.extract(entry));
                }
                return newOne;
            }
        };
    }

    protected TransformRule<Collection<ValueType>, Collection<ValueType>> getCollectionFilterRule(final FilterRule<ValueType> rule) {
        return new TransformRule<Collection<ValueType>, Collection<ValueType>>() {
            @Override
            public Collection<ValueType> extract(Collection<ValueType> obj) {
                Collection<ValueType> newOne = new ArrayList<>();
                for (ValueType entry : obj) {
                    if (rule.apply(entry)) {
                        newOne.add(entry);
                    }
                }
                return newOne;
            }
        };
    }
}

abstract class FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> {

    protected ContainerTypeWithValueType container;

    protected FPContainer(ContainerTypeWithValueType container) {
        this.container = container;
    }

    public static <KeyType, ValueType> FPMapContainer<KeyType, ValueType> from(Map<KeyType, ValueType> container) {
        return new FPMapContainer<>(container);
    }

    public static <ValueType> FPCollectionContainer<ValueType> from(Collection<ValueType> container) {
        return new FPCollectionContainer<>(container);
    }

    public abstract <Out> Object map(TransformRule<ContainerIterableItemType, Out> rule);

    public abstract FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> filter(FilterRule<ContainerIterableItemType> rule);

    public abstract FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> concat(FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> another);

    public abstract FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> concat(ContainerTypeWithValueType another);

    public <Out> Out reduce(TransformRule<ContainerTypeWithValueType, Out> rule) {
        return rule.extract(container);
    }

    public ContainerTypeWithValueType get() {
        return container;
    }

    protected <ContainerTargetType> ContainerTargetType handleContainer(TransformRule<ContainerTypeWithValueType, ContainerTargetType> collectionMapRule) {
        if (collectionMapRule != null) {
            return collectionMapRule.extract(container);
        }

        return (ContainerTargetType) container;
    }
}

现在你可以像使用Java8Stream一样这样使用它:

代码语言:javascript
复制
TransformRule<Integer, String> integerStringTransform = new TransformRule<Integer, String>() {
    @Override
    public String extract(Integer obj) {
        return "" + obj;
    }
};

TransformRule<Collection<String>, String> collectionStringTransform = new TransformRule<Collection<String>, String>() {
    @Override
    public String extract(Collection<String> obj) {
        String result = "";
        for (String item : obj) {
            result += item;
        }

        return result;
    }
};

FilterRule<Integer> ltFourFilter = new FilterRule<Integer>() {
    @Override
    public boolean apply(Integer obj) {
        return obj != null && obj < 4;
    }
};

// ==============================================

String reduced;

// Collection case:
// `reduced` would be "123"
reduced = FPContainer.from(Arrays.asList(1, 4))
        .concat(FPContainer.from(Arrays.asList(2)))
        .concat(Arrays.asList(3))
        .filter(ltFourFilter)
        .map(integerStringTransform).reduce(collectionStringTransform);

// Map case:
reduced = FPContainer.from(stringIntegerHashMap)
        .filter(new FilterRule<Map.Entry<String, Integer>>() {
            @Override
            public boolean apply(Map.Entry<String, Integer> obj) {
                return obj.getKey().charAt(0) < 'c' && obj.getValue() < 4;
            }
        })
        .map(new TransformRule<Map.Entry<String,Integer>, String>() {
            @Override
            public String extract(Map.Entry<String, Integer> obj) {
                return ""+obj.getValue();
            }
        }).reduce(new TransformRule<Map<String, String>, String>() {
            @Override
            public String extract(Map<String, String> obj) {
                String result = "";

                Map<String, String> objectStringMap = sortByValue(obj);
                for (Map.Entry<String, String> entry : objectStringMap.entrySet()) {
                    result += entry.getKey().toString() + entry.getValue();
                }

                return result;
            }
        });

附注:

sortByValue(地图)在这里:(来源:https://stackoverflow.com/a/109389/2293635)

代码语言:javascript
复制
public static <K, V> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Object>() {
        @SuppressWarnings("unchecked")
        public int compare(Object o1, Object o2) {
            return ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()).compareTo(((Map.Entry<K, V>) (o2)).getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<>();
    for (Iterator<Map.Entry<K, V>> it = list.iterator(); it.hasNext();) {
        Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
        result.put(entry.getKey(), entry.getValue());
    }

    return result;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30055585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档