bisorniyesordum
bisorniyesordum

Reputation: 119

Splitting elements to different number of lists in Java?

I have a problem with separating elements to different lists in Java. The problem is actually I need uncertain number of new lists. For example I have a method which returns a list contains some number of objects but if I have 50 elements in that list I want to split them to the small lists. For 50 elements I will need 10 new lists to put these elements inside but if that number will increase to 100 I will need 20 new lists. Is there any way to say Java automatically generate a new list for me if it is needed?

Upvotes: 1

Views: 112

Answers (1)

Stuart Marks
Stuart Marks

Reputation: 132380

It sounds like you want what is often called a "grouping" operation. To take your simplified example (from the comments), you have a bunch of Customer objects and you want to group them into separate lists categorized by City. (Your real problem may be more complex than this, but let's run with the City example for the moment.)

To have an arbitrary number of lists, a convenient way for organizing them is to create a Map<City, List<Customer>>. That is, you have a map whose key is City and whose value is a List of Customer objects that are from that City.

It's fairly straightforward to write an ordinary loop that runs through an input List<Customer> and stores them into Map as I've described above. A small wrinkle is that you have to handle creating the List and putting it into the Map the first time you encounter a Customer from a City that you haven't seen before. Here's the code:

List<Customer> inputList = ...;
Map<City, List<Customer>> map = new HashMap<>();
for (Customer cust : inputList) {
    City city = cust.getCity();
    List<Customer> custList = map.get(city);
    if (custList == null) {
        custList = new ArrayList<>();
        map.put(city, custList);
    }
    custList.add(cust);
}

In Java 8, you can use new method Map.computeIfAbsent() to save a bit of trouble with handling the special case of creating the list for the first customer from a city:

Map<City, List<Customer>> map = new HashMap<>();
for (Customer cust : inputList) {
    City city = cust.getCity();
    map.computeIfAbsent(city, k -> new ArrayList<>());
    map.get(city).add(cust);
}

But if you're using Java 8, you might as well use the Streams API, which has a Collectors class that can do this kind of grouping very conveniently:

Map<City, List<Customer>> map =
    inputList.stream()
        .collect(Collectors.groupingBy(Customer::getCity));

Upvotes: 1

Related Questions