Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6971925
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T16:54:08+00:00 2026-05-27T16:54:08+00:00

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

  • 0

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

public static <E> List<List<E>> group(final List<E> list, final GroupFunction<E> groupFunction) {

    List<List<E>> result = Lists.newArrayList();

    for (final E element : list) {

        boolean groupFound = false;
        for (final List<E> group : result) {
            if (groupFunction.sameGroup(element, group.get(0))) {
                group.add(element);
                groupFound = true;
                break;
            }
        }
        if (! groupFound) {

            List<E> newGroup = Lists.newArrayList();
            newGroup.add(element);
            result.add(newGroup);
        }
    }

    return result;
}

public interface GroupFunction<E> {
    public boolean sameGroup(final E element1, final E element2);
}

Is there a better way to do this, preferably by using guava?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T16:54:09+00:00Added an answer on May 27, 2026 at 4:54 pm

    Sure it is possible, and even easier with Guava 🙂 Use Multimaps.index(Iterable, Function):

    ImmutableListMultimap<E, E> indexed = Multimaps.index(list, groupFunction);
    

    If you give concrete use case it would be easier to show it in action.

    Example from docs:

    List<String> badGuys =
       Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
    Function<String, Integer> stringLengthFunction = ...;
    Multimap<Integer, String> index =
       Multimaps.index(badGuys, stringLengthFunction);
    System.out.println(index);
    

    prints

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

    In your case if GroupFunction is defined as:

    GroupFunction<String> groupFunction = new GroupFunction<String>() {
      @Override public String sameGroup(final String s1, final String s2) {
        return s1.length().equals(s2.length());
      }
    }
    

    then it would translate to:

    Function<String, Integer> stringLengthFunction = new Function<String, Integer>() {
      @Override public Integer apply(final String s) {
        return s.length();
      }
    }
    

    which is possible stringLengthFunction implementation used in Guava’s example.


    Finally, in Java 8, whole snippet could be even simpler, as lambas and method references are concise enough to be inlined:

    ImmutableListMultimap<E, E> indexed = Multimaps.index(list, String::length);
    

    For pure Java 8 (no Guava) example using Collector.groupingBy see Jeffrey Bosboom’s answer, although there are few differences in that approach:

    • it doesn’t return ImmutableListMultimap but rather Map with Collection values,
    • There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned (source),

    • it’s a bit more verbose than Guava + method reference.

    EDIT: If you don’t care about indexed keys you can fetch grouped values:

    List<List<E>> grouped = Lists.transform(indexed.keySet().asList(), new Function<E, List<E>>() {
            @Override public List<E> apply(E key) {
                return indexed.get(key);
            }
    });
    
    // or the same view, but with Java 8 lambdas:
    List<List<E>> grouped = Lists.transform(indexed.keySet().asList(), indexed::get);
    

    what gives you Lists<List<E>> view which contents can be easily copied to ArrayList or just used as is, as you wanted in first place. Also note that indexed.get(key) is ImmutableList.

    // bonus: similar as above, but not a view, instead collecting to list using streams:
    List<List<E>> grouped = indexed.keySet().stream()
        .map(indexed::get)
        .collect(Collectors.toList());
    

    EDIT 2: As Petr Gladkikh mentions in comment below, if Collection<List<E>> is enough, above example could be simpler:

    Collection<List<E>> grouped = indexed.asMap().values();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

What I want to do: Group all the like elements on a page (of
I have this scenario. I want group on Country and Category. A store can
I have a list but in this list there are lots of elements which
I have addres book app, and want to write the final result into a
I want to get the positions and lengths of the elements in a list.
I have an array which prints the list of some elements. I want to
<Results> <ResultSet>nothing special Description=More of nothing <Results> <Result> <Body>Four in this group</Body> <Body2>this is
I have a huge group of lists within lists that I want to combine:
I want to use Data.List.groupBy to group a list of tuples based on the
I want to display a list with tags plus the number of elements (in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.