Maven无法使用一系列流操作来编译java

时间:2016-05-30 22:25:12

标签: java eclipse maven intellij-idea java-stream

像标题所说的那样,当我尝试编译一段具有一系列流操作的代码时,我遇到了问题。

这在IDE中没有发生(尝试使用eclipse和IntelliJ)但是当我在控制台中尝试'mvn clean install'时,它会抛出以下错误:

[ERROR] .collect(Collectors.joining("&"));
[ERROR] ^^^^^^^

[ERROR] The method collect(Collector<? super Object,A,R>) in the type Stream<Object> is not applicable for the arguments (Collector<CharSequence,capture#1-of ?,String>)
[ERROR] 
[ERROR] Found 1 error and 0 warnings.
[ERROR] -> [Help 1]

测试代码:

package com.stackoverflow.test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamMavenTest {


    public static void main(String[] args) {
        List<Department> depts = initDepts();
        String unpaidReferences = depts.stream()
                .flatMap(dpto -> dpto.people.stream()
                        .filter(ppl -> ppl.lastname != null && ppl.name != null)
                        .map(ppl -> ppl.name + "|" + ppl.lastname))
                .collect(Collectors.joining("&"));
        System.out.println(unpaidReferences);
    }

    private static List<Department> initDepts() {
        List<Department> depts = new ArrayList<Department>();
        Department dep1 = new Department();
        dep1.people = new ArrayList<Person>();
        dep1.people.add(new Person("Baudouin","Quy"));
        dep1.people.add(new Person("Sigmund","Zebedaios"));
        dep1.people.add(new Person("Bernd","Edwyn"));
        depts.add(dep1);
        Department dep2 = new Department();
        dep2.people = new ArrayList<Person>();
        dep2.people.add(new Person("Olanrewaju","Jorgen"));
        dep2.people.add(new Person("Stanislovas","Adalberto"));
        dep2.people.add(new Person("Manuel","'Avshalom"));
        depts.add(dep2);
        return depts;
    }

    public static class Department{
        List<Person> people;
    }


    public static class Person{
        String name;
        String lastname;

        public Person(String name, String lastname){
            this.name = name;
            this.lastname = lastname;
        }
    }

}

现在,如果我更改主要方法:

public static void main(String[] args) {
  List<Department> depts = initDepts();
  Stream<String> flatMap = depts.stream()
          .flatMap(dpto -> dpto.people.stream()
                  .filter(ppl -> ppl.lastname != null && ppl.name != null)
                  .map(ppl -> ppl.name + "|" + ppl.lastname));
  String unpaidReferences = flatMap
          .collect(Collectors.joining("&"));
  System.out.println(unpaidReferences);
}

效果很好。

要记住的事情:

  • IDE和Maven都使用相同的Java版本。
  • Java版本:1.8.0_60。
  • Maven版本:3.3.3。

  • 主要执行的控制台输出:Baudouin | Quy&amp; Sigmund | Zebedaios&amp; Bernd | Edwyn&amp; Olanrewaju | Jorgen&amp; Stanislovas | Adalberto&amp; Manuel |'Avshalom

任何人都知道为什么会这样?我相信它与flatMap和lambda中的流有关,但我不确定。

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

在调用mvn之前尝试导出JAVA_HOME。似乎你有java7作为默认值。