TheWandererr
TheWandererr

Reputation: 514

Connect two ArrayLists with each other

I am pretty new to Java and i have a hard time solving this problem.

Lets say i have two Arraylists personIdList and titlelist which gets filled by a Database with the help of a ResultSet Object iteration.

personIdList.add(repPersonId.getLong("personID"));
titelList.add(repTitel.getString("titel"));

The first Arraylist(personIdList) contains Ids from different composer's like so :

[34, 34, 34, 37, 38, 133, 232, 232, 285, 285, 285, 285]

The second List(titlelist) contains Title's from that composer like so :

[Symphonie, Sinfonia Concertante, Oper, Symphonie, Ouverture zur Oper, Ouverture zur Oper, Konzert für zwei Klaviere, Sinfonie, Chöre aus der Schauspielmusik, Requiem, Klavierkonzert, Klavierkonzert]

Can i somehow establish a connection between those arrays? Because the composer id should be connectet to the corresponding Title.

For example(pseudo Code): personIdList.get(34) should give me all Titles that are connected to the Id 34.

Do i have to use ArrayLists or is there already something that does that?

Upvotes: 1

Views: 1179

Answers (4)

Harish Barma
Harish Barma

Reputation: 634

There is a good collection framework in Guava(provided by Google) library. If you are flexible to use external jars then use a multilistmap from guava library

ListMultimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(repPersonId.getLong("personID"),(repTitel.getString("titel"));

So what it does is it accepts more than one value for one key and stores that in a list.

If you want the list of keys you can get them as Set by calling

Set<Integer> keyset=multimap.getKeySet();

While retrieving the values from the multimap it returns the list result

List<String> personTitles = multimap.get(personId);

This way you can retrieve the data so no need of creating a list and setting it to the map and this makes it easier to read than a map of array lists

If you even want all the values in your case titles you can get it by

Collection<String> titles=multimap.values();

Anyway collection can be casted to Set if you don't want duplicates or List if you want all values in mulimap irrespective of duplicates.

So I think this will be very handy and easily understandable compared to map of arraylists

Upvotes: 2

Adrian
Adrian

Reputation: 3134

You can write your own collector which will create the desired map:

Map<Integer, List<String>> groupedIds = personIdList.stream()
   .collect(new CustomCollector(titlelist.iterator()));
groupedIds.get(34); // [Symphonie, Sinfonia Concertante, Oper]

Bellow is the custom collector.

public class CustomCollector implements Collector<Integer, Map<Integer, List<String>>, Map<Integer, List<String>>> {
   private Iterator<String> iterator;

   public CustomCollector(Iterator<String> iterator) {
      this.iterator = iterator;
   }

   @Override
   public Supplier<Map<Integer, List<String>>> supplier() {
      return HashMap::new;
   }

   @Override
   public BiConsumer<Map<Integer, List<String>>, Integer> accumulator() {
    return (map, id) -> {
        List<String> list = map.get(id);
        if(list == null) {
            list = new ArrayList<>();
            list.add(iterator.next());
            map.put(id, list);
        } else {
            list.add(iterator.next());
        }
    };
   }

   @Override
   public BinaryOperator<Map<Integer, List<String>>> combiner() {
      return (m1, m2) -> m1;
   }
   @Override
   public Function<Map<Integer, List<String>>, Map<Integer, List<String>>> finisher() {
      return HashMap::new;
   }
   @Override
   public Set<Characteristics> characteristics() {
      return Collections.emptySet();
   }
 }

Upvotes: 2

Ognjen Mišić
Ognjen Mišić

Reputation: 1416

As RC said. If you're not going to ORM Map it, you can iterate the id list and create a new Map (a key-value pair collection):

Map<Integer, List<String> personTitles = new HashMap<>();
for(Integer id: personIdList) {
    // your solution for retrieving the titles from the database
    // i would imagine you're using an entityManager.query or something which returns the result set of the titles
    // where you have to pass the `id` as a parameter
    // and get the list of titles and store them in a List<String>

    personTitles.put(id, `your retrieved List<String>`);
}

And then you can just say personTitles.get(32) which should retrieve your list of titles.

If you can post more code of how you retrieve entries from the database, that would be helpful.

Upvotes: 2

Leonardocregis
Leonardocregis

Reputation: 95

Usually you should use a object and fill it.... normaly a ORM mapping or so..

But, if you want a homemade soluction, at least the id of the Arrays matches ? Like arr1.get(1) is related to the arr2.get(1) ?

Upvotes: 1

Related Questions