java8-Collect(join,group,tolist,toSet,toMap)

  • collect在流中生成列表,map,等常用的数据结构
  • toList()
  • toSet()
  • toMap()
  • 自定义
 /**
 * toList
 */
 public static void toListTest(){
 List data = Data.getData();
 List collect = data.stream()
 .map(PersonModel::getName)
 .collect(Collectors.toList());
 }

 /**
 * toSet
 */
 public static void toSetTest(){
 List data = Data.getData();
 Set collect = data.stream()
 .map(PersonModel::getName)
 .collect(Collectors.toSet());
 }

 /**
 * toMap
 */
 public static void toMapTest(){
 List data = Data.getData();
 Map collect = data.stream()
 .collect(
 Collectors.toMap(PersonModel::getName, PersonModel::getAge)
 );

 data.stream()
 .collect(Collectors.toMap(per->per.getName(), value->{
 return value+"1";
 }));
 }

 /**
 * 指定类型
 */
 public static void toTreeSetTest(){
 List data = Data.getData();
 TreeSet collect = data.stream()
 .collect(Collectors.toCollection(TreeSet::new));
 System.out.println(collect);
 }

 /**
 * 分组
 */
 public static void toGroupTest(){
 List data = Data.getData();
 Map> collect = data.stream()
 .collect(Collectors.groupingBy(per -> "男".equals(per.getSex())));
 System.out.println(collect);
 }

 /**
 * 分隔
 */
 public static void toJoiningTest(){
 List data = Data.getData();
 String collect = data.stream()
 .map(personModel -> personModel.getName())
 .collect(Collectors.joining(",", "{", "}"));
 System.out.println(collect);
 }

 /**
 * 自定义
 */
 public static void reduce(){
 List collect = Stream.of("1", "2", "3").collect(
 Collectors.reducing(new ArrayList(), x -> Arrays.asList(x), (y, z) -> {
 y.addAll(z);
 return y;
 }));
 System.out.println(collect);
 }

你可能感兴趣的:(java8-Collect(join,group,tolist,toSet,toMap))