如何转换列表<a> to TreeSet<b>

时间:2016-06-07 10:35:55

标签: java

What is the best way to transform List<A> aList to TreeSet<B>, where for A a we have the following mapping B b=a.getElement()?

2 个答案:

答案 0 :(得分:4)

假设listA的列表

,可以在Java 8中这样做
list.stream().map(A::getElement).collect(toCollection(TreeSet::new))

答案 1 :(得分:2)

如果您使用的是Java8,则可以使用stream api

TreeSet<B> listB = listA.stream()
                .map(a -> a.getElement())
                .collect(Collectors.toCollection(TreeSet::new));

如果你必须处理pre-lambda环境,我的建议是创建接口

interface Converter<S, T> {
        T convert(S source);
    }

漂亮的实用程序类

class ConvertColection {
        public static <S, T> TreeSet<T> toTreeset(Collection<S> source,
                Converter<S, T> converter) {
            TreeSet<T> result = new TreeSet<T>();
            for (S s : source) {
                result.add(converter.convert(s));
            }
            return result;
        }
    }

你可以扩展它以添加更多方法,或者使它们更通用,即通过传递集合类并在方法中实例化它。

然后你将通过调用

执行此操作
TreeSet<B> listB = ConvertColection.toTreeset(listA, 
            new Converter<A, B>() {
                    @Override
                    public B convert(A a) {
                        return a.getElement();
                    }
        }); 

您还可以将转换器创建为单例并重复使用它们。 显然,thera是一堆库,可以为你做这个

相关问题