Created
February 14, 2017 01:17
-
-
Save hayukleung/73b8b9f37b2d3e126ab3fe6da0e7600b to your computer and use it in GitHub Desktop.
集合分组方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.chargerlink.app.utils; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
/** | |
* chargerlink_v3 | |
* com.chargerlink.app.utils | |
* CollectionUtils.java | |
* | |
* by hayukleung | |
* at 2017-02-08 14:36 | |
*/ | |
/** | |
* Java集合通用方法 | |
*/ | |
public class CollectionUtils { | |
/** | |
* 依据K将List<V>分组 | |
* | |
* @param list | |
* @param <V> | |
* @return a list | |
*/ | |
public static <V extends Groupable> List<List<V>> groupAsList(List<V> list) { | |
List<List<V>> result = new ArrayList<>(); | |
Map<Integer, List<V>> group = groupAsMap(list); | |
for (Integer key : group.keySet()) { | |
result.add(group.get(key)); | |
} | |
return result; | |
} | |
/** | |
* 依据K将List<V>分组 | |
* | |
* @param list | |
* @param <V> | |
* @return a map | |
*/ | |
public static <V extends Groupable> Map<Integer, List<V>> groupAsMap(List<V> list) { | |
Map<Integer, List<V>> group = new HashMap<>(); | |
if (null == list || 0 == list.size()) { | |
return group; | |
} | |
for (V v : list) { | |
if (!group.containsKey(v.getGroupableKey())) { | |
List<V> vList = new ArrayList<>(); | |
vList.add(v); | |
group.put(v.getGroupableKey(), vList); | |
} else { | |
group.get(v.getGroupableKey()).add(v); | |
} | |
} | |
return group; | |
} | |
public static interface Groupable { | |
int getGroupableKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment