简体   繁体   中英

Filtering List objects by object type

I have a List of Objects (ordered) which are already grouped by object type.

List<Object> myList = new ArrayList();
myList.add(new Integer());
myList.add(new Integer());
myList.add("string");
myList.add(new Double());
myList.add(new Double());
myList.add(new Double());

How can I elegantly loop through the groups of objects without using instanceof operator?

I essentially want this:

List<List<Object>> result;

I do not know what object types there are, so the simpleton approach would be to loop like this:

Object obj = iter.next();
String thisClass = obj.class.getSimpleName();
if (!thisClass.equals(lastClass)){
  currentList = new ArrayList();
}
currentList.add(obj);

however perhaps a stream would be nice, something like:

myList.stream().collect(Collectors.groupingBy(Class::getSimpleName, Collectors.<IBaseDO>toList()));

yes this results in a compile error as I can't get the syntax just right.

Ideas?

This is a very bad design.

Yet, you can do:

List<List<Object>> grouped = 
    myList.stream()
          .collect(collectingAndThen(
                       groupingBy(Object::getClass, LinkedHashMap::new, toList()), 
                       map -> new ArrayList<>(map.values)
          ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM