Java: Converting lists of one element type to a list of another type

前端 未结 9 604
借酒劲吻你
借酒劲吻你 2021-02-01 21:18

I\'m writing an adapter framework where I need to convert a list of objects from one class to another. I can iterate through the source list to do this as in

Java: Best

9条回答
  •  隐瞒了意图╮
    2021-02-01 21:52

    Lambdaj allows to do that in a very simple and readable way. For example, supposing you have a list of Integer and you want to convert them in the corresponding String representation you could write something like that;

    List ints = asList(1, 2, 3, 4);
    Iterator stringIterator = convertIterator(ints, new Converter {
        public String convert(Integer i) { return Integer.toString(i); }
    });
    

    Lambdaj applies the conversion function only while you're iterating on the result. There is also a more concise way to use the same feature. The next example works supposing that you have a list of persons with a name property and you want to convert that list in an iterator of person's names.

    Iterator namesIterator = convertIterator(persons, on(Person.class).getName());
    

    Pretty easy. Isn't it?

提交回复
热议问题