(澳门正规博彩十大网站) 请问java 结果集list,根据user.name属性,如何再将name属性相同的user放到一个新的list中?

请问java 结果集list<user>,根据user.name属性,如何再将结果集中的name属性相同的user放到一个新的list中?
user的name可能多个,不固定,根据name将user放到不同新的的list

拿来练习下RxJava

List<User> all = getUserList;
Observable.fromall .groupByu -> u.name .flatMapg -> g.toList .subscribelist -> { System.out.printlnlist.get0.name + ":"; for User u : list { System.out.printlnu; } System.out.println; };

直接写点代码了
`

public class MyTest { class User{ String name; int age; public UserString name,int age { this.name = name; this.age = age; } } public static void mainString[] args { MyTest myTest = new MyTest; List<User> users = new ArrayList<>; User user1 = myTest.new User"zhangsan", 18; User user2 = myTest.new User"lisi", 18; User user3 = myTest.new User"wangwu", 18; User user4 = myTest.new User"zhangsan", 19; User user5 = myTest.new User"zhangsan", 20; User user6 = myTest.new User"lisi", 19; users.adduser1; users.adduser2; users.adduser3; users.adduser4; users.adduser5; users.adduser6; /*根据name将user放到不同新的的list*/ Map map = new HashMap<String,List<User>>; for User user : users{ //如果map中不存此name,则以此name为key ifmap.getuser.name == null { List list = new ArrayList<User>; list.adduser; map.putuser.name,list; }else{ List list = List<User> map.getuser.name; list.adduser; map.putuser.name,list; } } List<User> zhangsans = List<User>map.get"zhangsan"; for User user : zhangsans{ System.out.printlnuser.name+" : "+user.age; } System.out.printlnmap.get"zhangsan"; }
}

`

new List<user>不就好了?

使用 Map<String,List<User>>, name 作为key ,遍历原list 并且根据name 获取 对应的 list 把 user 添加进去,如果不存在就创建并保存到 Map 中。
手机码字不便… 将就着看吧…

java8

List<User> users = ...;
Map<String, List<User>> usersGroupByName = users.stream.collectCollectors.groupingByUser::getName;

guava

/** * 根据函数 O->K和O->V 把 O[] 转化为 {K -> V[]}的Multimap */
public static <O, K, V> ArrayListMultimap<K, V> newMultimapWithValueCollection<? extends O> coll, Function<O, K> objToKeyFunction, Function<O, V> objToValueFunction { // 可以根据需求把ArrayListMultimap换成HashMultimap或TreeMultimap ArrayListMultimap<K, V> result = ArrayListMultimap.create; if coll == null || coll.isEmpty { return result; } for O obj : coll { K key = objToKeyFunction.applyobj; V value = objToValueFunction.applyobj; result.putkey, value; } return result;
} List<User> users = ...;
ArrayListMultimap<String, User> usersGroupByName = newMultimapWithValueusers, User::getName, v -> v;

参考资料:

ifeve.com/google-guava/

GoldyMark的Java8的写法不错,非常简洁。

发表评论

电子邮件地址不会被公开。 必填项已用*标注