相关疑难解决方法(0)

Java 8将<V>列入Map <K,V>

我想使用Java 8的流和lambdas将对象列表转换为Map.

这就是我在Java 7及以下版本中编写它的方法.

private Map<String, Choice> nameMap(List<Choice> choices) {
        final Map<String, Choice> hashMap = new HashMap<>();
        for (final Choice choice : choices) {
            hashMap.put(choice.getName(), choice);
        }
        return hashMap;
}
Run Code Online (Sandbox Code Playgroud)

我可以使用Java 8和Guava轻松完成此任务,但我想知道如何在没有Guava的情况下完成此操作.

在番石榴:

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, new Function<Choice, String>() {

        @Override
        public String apply(final Choice input) {
            return input.getName();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

还有Java 8 lambda的番石榴.

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}
Run Code Online (Sandbox Code Playgroud)

java lambda java-8 java-stream

892
推荐指数
16
解决办法
60万
查看次数

按对象值分组,计数然后按最大对象属性设置组密钥

我已经设法使用Java 8 Streams API编写解决方案,该解决方案首先按对象组合对象Route列表,然后计算每个组中对象的数量.它返回一个映射Route - > Long.这是代码:

Map<Route, Long> routesCounted = routes.stream()
                .collect(Collectors.groupingBy(gr -> gr, Collectors.counting()));
Run Code Online (Sandbox Code Playgroud)

而Route类:

public class Route implements Comparable<Route> {
    private long lastUpdated;
    private Cell startCell;
    private Cell endCell;
    private int dropOffSize;

    public Route(Cell startCell, Cell endCell, long lastUpdated) {
        this.startCell = startCell;
        this.endCell = endCell;
        this.lastUpdated = lastUpdated;
    }

    public long getLastUpdated() {
        return this.lastUpdated;
    }

    public void setLastUpdated(long lastUpdated) {
        this.lastUpdated = lastUpdated;
    }

    public Cell getStartCell() {
        return startCell;
    }

    public void setStartCell(Cell startCell) …
Run Code Online (Sandbox Code Playgroud)

java grouping java-8 java-stream

18
推荐指数
2
解决办法
1万
查看次数

标签 统计

java ×2

java-8 ×2

java-stream ×2

grouping ×1

lambda ×1