cadmy
cadmy

Reputation: 535

How to "append" new field/data into an object without creating a new class nor modifying the class?

I have a method which calculates an integer for every row in a bean MyPeriod. I don't want to change the class MyPeriod, to create a new class or to have two lists but I need to return some list which contains the list of MyPeriod with a new column. What is the ways to deal with this issue?

public ??? bindNewColumn (List<MyPeriod> periods) {
   List<Integer> newList = new ArrayList<>();
   for (MyPeriod period : periods) {
      newList.add(calculation(period));
   }

   return ???;
}

Upvotes: 1

Views: 1041

Answers (4)

user180100
user180100

Reputation:

With a Pair.

public List<Pair<MyPeriod, Integer>> bindNewColumn(List<MyPeriod> periods) {
   final List<Pair<MyPeriod, Integer>> newList = new ArrayList<>();
   for (MyPeriod period : periods) {
      newList.add(Pair.of(period, calculation(period)));
   }

   return newList;
}

Upvotes: 1

TheCodingFrog
TheCodingFrog

Reputation: 3514

public Map<MyPeriod, Integer> bindNewColumn (List<MyPeriod> periods) {
       Map<MyPeriod, Integer> map = new HashMap<MyPeriod, Integer>();
       for (MyPeriod period : periods) {
           map.put(period, calculation(period));
       }
       return map;
    }

Upvotes: 0

Dici
Dici

Reputation: 25960

If you are using JDK7 or later, you can use javafx.util.Pair :

public Pair<List<MyPeriod>,List<Integer>> bindNewColumn (List<MyPeriod> periods) {
    ...
    return new Pair<List<MyPeriod>,List<Integer>>(periods,newList);
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

You have listed the good alternatives - creating a new class and changing MyPeriod.

If you want a bad one, you could return an array, and let your callers assume that it has two items:

// This is a very dirty approach. Do not use in production.
public List[] bindNewColumn (List<MyPeriod> periods) {
    ...
    return new List[] { periods, newList };
}

If you know that all periods in List<MyPeriod> are different, and also that MyPeriod implements robust hashCode() and equals(), you could use LinkedHashMap<MyPeriod,Integer> to establish your mappings:

public LinkedHashMap<MyPeriod,Integer> bindNewColumn (List<MyPeriod> periods) {
    LinkedHashMap<MyPeriod,Integer> res = new LinkedHashMap<MyPeriod,Integer>();
    for (MyPeriod period : periods) {
        res.put(period, calculation(period));
    }
    return res;
}

Upvotes: 2

Related Questions