【问题标题】:functional way to accumulate pairs in java8在java8中累积对的功能方法
【发布时间】:2015-06-12 16:36:43
【问题描述】:

以下是一些我试图将其转换为函数式编程代码的命令式代码:

public class Person {
    String name;
    Token token;

    public Person(String name, Token token) {
        this.name = name;
        this.token = token;
    }
}
public class Token {
    String id;
    boolean isValid;
    public Token(String id, boolean isValid) {
        this.id = id;
        this.isValid = isValid;
    }
    public String getId() { return id; }
    public boolean isValid() {return isValid;}
}
public static List<Token> getTokensForPerson(String name) {...}


public static List<Person> getPeople1 (String[] names) {

    List<Person> people = new ArrayList<Person> ();
    for (String name: names) {
        List<Token> tokens = getTokensForPerson(name);
        for (Token token: tokens) {
            if (token.isValid()) {
                people.add(new Person(name, token));
            }
        }

    }
    return people;
}

这是我尝试以实用的方式进行操作。

public static List<Person> getPeople2 (String[] names) {

    return Arrays.stream(names).map(name -> getTokensForPerson(name))
        .flatMap(tokens -> tokens.stream().filter(token -> token.isValid))
        .map(token -> new Person(name, token))   // <== compiler error here. "Cannot resolve symbol 'name'"
        .collect(Collectors.toList());
}

但是它没有编译,因为在最后一次映射操作中我需要参考name 来创建Person 对象,而name 当时不可用。有什么想法吗?

【问题讨论】:

  • “势在必行”更好:)

标签: java functional-programming java-8 java-stream


【解决方案1】:

您可以在flatMap 内移动map 步骤:

return Arrays.stream(names)
        .<Person>flatMap(
                name -> getTokensForPerson(name).stream()
                        .filter(Token::isValid)
                        .map(token -> new Person(name, token)))
        .collect(Collectors.toList());

这样您也可以访问name 变量。

基于StreamEx的解决方案更短,但需要第三方库:

return StreamEx.of(names)
               .cross(name -> getTokensForPerson(name).stream())
               // Here we have the stream of entries 
               // where keys are names and values are tokens
               .filterValues(Token::isValid)
               .mapKeyValue(Person::new)
               .toList();

【讨论】:

    【解决方案2】:

    是否可以创建 TokenExtended 类扩展 Token,并添加名称,并从 getTokensForPerson 返回 List&lt;TokenExtended&gt; 而不是 List&lt;Token&gt;

    public class TokenExtended extends Token {
        private String name;
        public TokenExtended(String name, String id, boolean isValid) {
            super(id, isValid);
            this.name = name;
        }
    }
    

    这样你的代码就可以工作了

        Arrays.stream(names).map(name -> getTokensForPerson(name)).flatMap(tokens -> tokens.stream().filter(token -> token.isValid))
                .map(token -> new Person(token.name, token)).collect(Collectors.toList());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多