7

让我向您展示我的代码:

Foo 类

public class Foo {

    String code;
    String value;

    public Foo(String code, String value) {
        super();
        this.code = code;
        this.value = value;
    }
    // getters/setters
}

主要方法(重点getFooMultiMapCode()方法):

public class FooMain {

public static void main(String[] args) {
    Foo foo1 = new Foo("100","foo1");
    Foo foo2 = new Foo("200","foo2");
    Foo foo3 = new Foo("300","foo3");
    Foo foo4 = new Foo("100","foo4");
    Foo foo5 = new Foo("100","foo5");
    Foo foo6 = new Foo("200","foo6");
    List<Foo> foos = Arrays.asList(foo1,foo2,foo3,foo4,foo5,foo6);  
    Map<String,List<Foo>> fooCodeMap = getFooMultiMapCode(foos);
    System.out.println(fooCodeMap);
}

private static Map<String, List<Foo>> getFooMultiMapCode(List<Foo> foos) {
    Map<String, List<Foo>> fooMultiMapCode = new HashMap<String, List<Foo>>();
    for(Foo foo:foos){
        List<Foo> list = fooMultiMapCode.get(foo.getCode());
        if(list==null){
            list = new ArrayList<Foo>();
            list.add(foo);
            fooMultiMapCode.put(foo.getCode(), list);
        }
        else {
            list.add(foo);
        }
    }
    return fooMultiMapCode;
}
}

Main 正确打印此字符串:

{100=[foo1, foo4, foo5], 200=[foo2, foo6], 300=[foo3]}

我想以getFooMultiMapCode更简洁的方式重写方法,例如使用 java8 或 lambdaj、guava 等库,但我不想更改方法签名

4

2 回答 2

11

Java 8 的解决方案和groupingBy(classifier, downstream)

return foos.stream().collect(Collectors.groupingBy(Foo::getCode, Collectors.toList()));

或者只是groupingBy(classifier)@Boris the Spider注意到的那样:

return foos.stream().collect(Collectors.groupingBy(Foo::getCode));
于 2016-11-05T13:22:20.903 回答
1

在@Holgers 评论上扩展一点:如果您更喜欢循环,则为非流版本 -java8尽管如此:

private static Map<String, List<Foo>> getFooMultiMapCode(List<Foo> foos) {
    Map<String, List<Foo>> fooMultiMapCode = new HashMap<String, List<Foo>>();
    for(Foo foo : foos){
        fooMultiMapCode.computeIfAbsent(foo.getCode(), x -> new ArrayList<>()).add(foo);
    }
    return fooMultiMapCode;
}

甚至

private static Map<String, List<Foo>> getFooMultiMapCode(List<Foo> foos) {
    Map<String, List<Foo>> fooMultiMapCode = new HashMap<String, List<Foo>>();
    foos.forEach(foo -> fooMultiMapCode.computeIfAbsent(foo.getCode(), x -> new ArrayList<>()).add(foo));
    return fooMultiMapCode;
}

不过,我仍然更喜欢流版本。

于 2016-11-07T14:20:08.313 回答