使⽤java8的stream流将List对象转成map键加对象
@Test
public void test2(){
List<User> users =new ArrayList();
users.add(new User("1","lhx","1"));
users.add(new User("2","sj","2"));
users.add(new User("3","tx","3"));
java streamMap<String, String> collect = users.stream().Map(User::getId, User::getName));
Map<String, User> collect1 = users.stream().Map(User::getId, Function.identity(),(v1, v2)->v1));
Map<String, User> collect2 = users.stream().Map(User::getId, Function.identity()));
ConcurrentHashMap<String, User> collect3 = users.stream().Map(User::getName, Function.identity(),(v1, v2)-> v1, ConcurrentH ashMap::new));
System.out.println(collect1);
System.out.println(collect2);
System.out.println(collect3);
}
输出:
{1=User(id=1, name=lhx, age=1), 2=User(id=2, name=sj, age=2), 3=User(id=3, name=tx, age=3)}
{1=User(id=1, name=lhx, age=1), 2=User(id=2, name=sj, age=2), 3=User(id=3, name=tx, age=3)}
{tx=User(id=3, name=tx, age=3), sj=User(id=2, name=sj, age=2), lhx=User(id=1, name=lhx, age=1)}
转成map映射当键的属性最好选择性的使⽤唯⼀id来充当键,这样好避免键冲突。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论