相关疑难解决方法(0)

通用类型推断无法使用方法链接?

此代码在Java 8中编译,但无法在Java 7中编译:

class Map<K,V> {
    static <K,V> Map<K,V> empty() {return null;}
    Map<K,V> put(K k, V v) {return null;}
    V get(K k) {return null;}
}

class A {
    static void f(Map<Integer,String> m){}
    public static void main(String[] args) {
        f(Map.empty());
    }
}
Run Code Online (Sandbox Code Playgroud)

它不会推断出Map返回的具体类型Map.empty():

$ javac7 A.java
A.java:10: error: method f in class A cannot be applied to given types;
        f(Map.empty());
        ^
  required: Map<Integer,String>
  found: Map<Object,Object>
  reason: actual argument Map<Object,Object> cannot be converted to Map<Integer,String> by method invocation …
Run Code Online (Sandbox Code Playgroud)

java generics type-inference java-7 java-8

27
推荐指数
1
解决办法
2334
查看次数

为什么Stream#reduce没有隐式接受处理超类型元素的累积函数?

考虑这些类和累积函数,它们代表了我原始上下文的简化(但是再现了同样的问题):

abstract static class Foo {
    abstract int getK();
}
static class Bar extends Foo {
    int k;
    Bar(int k) { this.k = k; }
    int getK() { return this.k; }
}

private static Foo combined(Foo a1, Foo a2) {
    return new Bar(a1.getK() + a2.getK());
}
Run Code Online (Sandbox Code Playgroud)

我试图通过依赖单独的函数来执行项目的累积(最初的数据索引报告)combined,该函数直接处理类型的元素Foo.

Foo outcome = Stream.of(1,2,3,4,5)
        .map(Bar::new)
        .reduce((a,b) -> combined(a, b))
        .get();
Run Code Online (Sandbox Code Playgroud)

事实证明,此代码导致编译错误(OpenJDK"1.8.0_92"):"lambda表达式中的错误返回类型:Foo无法转换为Bar".编译器坚持尝试使用Bar累积元素来减少流,即使Foo累积函数的参数和返回类型都有公共类型.

我还发现,只要我明确地将流映射到Foos 流中,我仍然可以采用这种方法:

Foo outcome = Stream.of(1,2,3,4,5)
        .<Foo>map(Bar::new)
        .reduce((a,b) -> combined(a, …
Run Code Online (Sandbox Code Playgroud)

java type-inference java-8 java-stream

14
推荐指数
3
解决办法
630
查看次数

Java何时需要显式类型参数?

鉴于:

import com.google.common.collect.ImmutableMap;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Stream;

public class Testcase
{
    public static <T, K, V> MapCollectorBuilder<T, K, V>
        toImmutableMap(Function<? super T, ? extends K> keyMapper,
            Function<? super T, ? extends V> valueMapper)
    {
        return null;
    }

    public static final class MapCollectorBuilder<T, K, V>
    {
        public Collector<T, ?, ImmutableMap<K, V>> build()
        {
            return null;
        }
    }

    public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap2(
        Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends …
Run Code Online (Sandbox Code Playgroud)

java java-8

13
推荐指数
1
解决办法
891
查看次数

在Java 8中对Comparator的误解

public class Test {
    public static void main(String[] args) {
        List<Pair<String, Integer>> list = new ArrayList<>();
        list.add(new Pair<>("1", 8));
        list.add(new Pair<>("3", 2));
        list.add(new Pair<>("2", 15));

        list.stream()
            .sorted(Comparator.comparingInt(p -> p.v))
            .map(p -> p.k)
            .forEach(System.out::println);

    }
}

class Pair<K, V> {
    K k;
    V v;
    public Pair(K k, V v) {
        this.k = k;
        this.v = v;
    }
}
Run Code Online (Sandbox Code Playgroud)

好的,正如您所了解的那样,此代码是从与最高值关联的最低值打印我的对键,因此我获得了预期的输出:

3 1 2

到现在为止还挺好.现在我想反过来,我想我只需要这样做

list.stream()
    .sorted(Comparator.comparingInt(p -> p.v).reversed())
    .map(p -> p.k)
    .forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)

但我得到一个编译错误:

v cannot be resolved or is not a field …
Run Code Online (Sandbox Code Playgroud)

java comparator java-8

12
推荐指数
1
解决办法
2453
查看次数

为什么这个Java 8流示例不能编译?

我想弄清楚为什么这段代码不能在JDK上编译1.8.0_45:

public class Example<E extends Example<E>> {
    public List<? extends Example<?>> toExamples(Collection<String> collection) {
        return collection.stream()
                .map(v -> lookup(v))
                .collect(Collectors.toList());
    }

    public static <E extends Example<E>> E lookup(String value) {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

添加一个看似不必要的演员修复了它:

public class Example<E extends Example<E>> {
    public List<? extends Example<?>> toExamples(Collection<String> collection) {
        return collection.stream()
                .map(v -> (Example<?>) lookup(v))
                .collect(Collectors.toList());
    }

    public static <E extends Example<E>> E lookup(String value) {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是编译器的错误:

Example.java:9: error: incompatible types: inference variable R has …
Run Code Online (Sandbox Code Playgroud)

java type-inference java-8 java-stream

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

比较然后比较给出编译错误

我正在尝试List按名称对员工进行排序,然后使用Java8 Comparator,我在下面创建Comparator但是它给了我一个编译器错误

Type mismatch: cannot convert from Comparator<Object> to <unknown>

    Comparator<String> c = Comparator.comparing(s -> s.split("\\s+")[0])
            .thenComparingInt(s -> Integer.parseInt(s.split("\\s+")[1])); //compile error
Run Code Online (Sandbox Code Playgroud)

但是如果我明确指定Type,它就可以工作

    Comparator<String> c = Comparator.<String, String> comparing(s -> s.split("\\s+")[0])
            .thenComparingInt(s -> Integer.parseInt(s.split("\\s+")[1])); //works
Run Code Online (Sandbox Code Playgroud)

或者通过创建两个Compartors和链

    Comparator<String> name = Comparator.comparing(s -> s.split("\\s+")[0]);
    Comparator<String> age = Comparator.comparingInt(s -> Integer.parseInt(s.split("\\s+")[1]));
    Comparator<String> cc = name.thenComparing(age); //works
Run Code Online (Sandbox Code Playgroud)

我已Comparator<String>在左侧指定了类型,但为什么自动类型推断未找到正确的类型并期望明确指定.

有人可以澄清一下吗?

这是代码

    String[] arr = { "alan 25", "mario 30", "alan 19", "mario 25" };
    Comparator<String> c = …
Run Code Online (Sandbox Code Playgroud)

java comparable comparator java-8

8
推荐指数
1
解决办法
2032
查看次数

无法在意外的地方推断出类型(可能是javac bug?)

在回答问题时,我遇到了Java类型推断的这种奇怪行为.以下工作没有问题:

new HashMap<String,Integer>().entrySet().stream()
                             .sorted(Map.Entry.comparingByValue());
Run Code Online (Sandbox Code Playgroud)

但如果我们.reversed()最后添加,它会突然失败:

new HashMap<String,Integer>().entrySet().stream()
                             .sorted(Map.Entry.comparingByValue().reversed());
Run Code Online (Sandbox Code Playgroud)

细节:在第一种情况下,comparingByValue()推断类型为Comparator<Map.Entry<String, Integer>>,但在第二种情况下,它更改为Comparator<Map.Entry<Object, V>>.

类型reversed()只是Comparator<T>对其目标类型的身份转换.为什么类型推断会在这样一个看似微不足道的步骤中失去它?我无法摆脱预感,这必定是由于推断机制中的一个错误.

作为进一步的难题,如果我们只是内联实现reversed(),那就是return Collections.reverseOrder(this);:

new HashMap<String,Integer>().entrySet().stream()
                             .sorted(reverseOrder(Map.Entry.comparingByValue());
Run Code Online (Sandbox Code Playgroud)

它又有效了.

java type-inference java-8

6
推荐指数
0
解决办法
98
查看次数

按值反转排序Map <String,Long>

我有一个Map<String, Long> map我希望Long使用Java 8的功能按相反顺序排序的值.使用Google我发现这个线程提供了这个解决方案

Map<String, Long> sortedMap = map.entrySet().stream()
           .sorted(comparing(Entry::getValue))
                     .collect(toMap(Entry::getKey, Entry::getValue,
                              (e1,e2) -> e1, LinkedHashMap::new));
Run Code Online (Sandbox Code Playgroud)

如果我想在评论中将订单反转,则表示要使用comparing(Entry::getValue).reversed()而不是comparing(Entry::getValue).

但是,代码不起作用.但是通过这种小小的适应性,它可以:

Map<String, Long> sortedMap = map.entrySet().stream()
          .sorted(Comparator.comparing(Entry::getValue))
                .collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                      (e1, e2) -> e1, LinkedHashMap::new));
Run Code Online (Sandbox Code Playgroud)

我是否必须先进行一些导入才能运行原始代码?

从那以后,仍然有什么可以得到颠倒的顺序

Map<String, Long> sortedMap = map.entrySet().stream()
          .sorted(Comparator.comparing(Entry::getValue).reversed())
                .collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                      (e1, e2) -> e1, LinkedHashMap::new));
Run Code Online (Sandbox Code Playgroud)

给出了一条错误信息:

The type Map.Entry does not define getValue(Object) that is applicable here
Run Code Online (Sandbox Code Playgroud)

sorting dictionary java-8 java-stream

5
推荐指数
1
解决办法
1558
查看次数

在这种情况下,我如何处理 Function&lt;T, R&gt; 和省略号/可变参数?

我的一个项目是throwing-lambdas;在其中,我的目标是简化@FunctionalInterfaces 中潜在s的使用Stream,其在流中使用的唯一“缺陷”是它们抛出已检查的异常(就我而言,我宁愿称其为有缺陷的事实,即您不能抛出已检查的异常来自流,但那是另一个故事)。

所以,因为Function<T, R>我定义了这个:

@FunctionalInterface
public interface ThrowingFunction<T, R>
    extends Function<T, R>
{
    R doApply(T t)
        throws Throwable;

    default R apply(T t)
    {
        try {
            return doApply(t);
        } catch (Error | RuntimeException e) {
            throw e;
        } catch (Throwable throwable) {
            throw new ThrownByLambdaException(throwable);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这允许我定义,例如:

final ThrowingFunction<Path, Path> = Path::toRealPath;
Run Code Online (Sandbox Code Playgroud)

(为什么Path::toRealPath......好吧,正是因为它有一个省略号)。

不想停在这里,我希望能够写出这样的东西:

Throwing.function(Path::toRealPath).fallbackTo(Path::toAbsolutePath)
Run Code Online (Sandbox Code Playgroud)

以上几乎有效......继续阅读。

我也这样定义:

public abstract class Chainer<N, T extends N, C extends Chainer<N, …
Run Code Online (Sandbox Code Playgroud)

java lambda variadic-functions java-8 java-stream

4
推荐指数
2
解决办法
456
查看次数

Java 8 - 初始化列表(列表)

我有一个关于Java 8和列表的问题.是否可以比下面的代码更容易初始化List?

final List<List<ScheduleIntervalContainer>> weekScheduler = new ArrayList<>();

weekScheduler.add(0, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(1, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(2, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(3, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(4, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(5, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(6, new ArrayList<ScheduleIntervalContainer>());
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

0
推荐指数
2
解决办法
226
查看次数