Grouping elements of a list into sublists (maybe by using guava)

后端 未结 4 2012
南笙
南笙 2020-12-13 00:44

I want to group elements of a list. I\'m currently doing it this way:

public static  List> group(final List list, fina         


        
4条回答
  •  别那么骄傲
    2020-12-13 01:09

    Collector.groupingBy from the Java 8 streams library provides the same functionality as Guava's Multimaps.index. Here's the example in Xaerxess's answer, rewritten to use Java 8 streams:

    List badGuys = Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
    Map> index = badGuys.stream()
        .collect(Collectors.groupingBy(String::length));
    System.out.println(index);
    

    This will print

    {4=[Inky], 5=[Pinky, Pinky, Clyde], 6=[Blinky]}
    

    If you want to combine the values with the same key in some other way than creating a list, you can use the overload of groupingBy that takes another collector. This example concatenates the strings with a delimiter:

    Map index = badGuys.stream()
        .collect(Collectors.groupingBy(String::length, Collectors.joining(" and ")));
    

    This will print

    {4=Inky, 5=Pinky and Pinky and Clyde, 6=Blinky}
    

    If you have a large list or your grouping function is expensive, you can go parallel using parallelStream and a concurrent collector.

    Map> index = badGuys.parallelStream()
        .collect(Collectors.groupingByConcurrent(String::length));
    

    This may print (the order is no longer deterministic)

    {4=[Inky], 5=[Pinky, Clyde, Pinky], 6=[Blinky]}
    

提交回复
热议问题