【20005】Java 8 Stream/Collect 使用示例

  • 将一个数组转为另一个对象数组
public static void main(String[] args) {
    // old
    List myColors = new ArrayList<>();
    for (Colors color : Colors.values()) {
        myColors.add(new MyColor(color.name(),color.getColorValue().asHex()));
    }
    // java 8
    List collect = Arrays.stream(Colors.values())
            .map(t -> new MyColor(t.name(),t.getColorValue().asHex()))
            .collect(Collectors.toList());

    System.out.println(JSON.toJSONString(collect));
}

@Data
@AllArgsConstructor
@NoArgsConstructor
static
class MyColor{
    String name;
    String hexCode;
}
  • 分组求和、统计
public static void main(String[] args) {
    List people = new ArrayList() {{
        add(new Person(0, 1));
        add(new Person(0, 2));
        add(new Person(0, 3));
        add(new Person(1, 4));
        add(new Person(1, 5));
    }};
    Map sumCollect ;
    Map countCollect ;

        // 1.8
    // sumCollect = new HashMap<>();
    // countCollect = new HashMap<>();
    // people.forEach(s->{
        // sumCollect.put(s.getSex(), sumCollect.getOrDefault(s.getSex(), 0)+1);
        // countCollect.put(s.getSex(), (long) (sumCollect.getOrDefault(s.getSex(), 0) +sumCollect.getOrDefault(s.getSex(), 0)));
    // });

    // 1.8 stream
    sumCollect = people.stream().collect(Collectors.groupingBy(
            Person::getSex, Collectors.summingInt(Person::getAge)
    ));
    countCollect = people.stream().collect(Collectors.groupingBy(
            Person::getSex, Collectors.counting()
    ));

    System.out.println(JSON.toJSONString(sumCollect));
    System.out.println(JSON.toJSONString(countCollect));
}

@Data
@AllArgsConstructor
@NoArgsConstructor
static
class Person{
    Integer sex;
    Integer age;
}

console:
{0:3,1:2}
{0:6,1:4}
  • 校验数据有效性
 public static void main(String[] args) {
    JSONArray ja = new JSONArray();
    JSONObject jo ;

    jo = new JSONObject();
    jo.put("id", 1);
    jo.put("key_a", "val_a");
    jo.put("key_b", "");
    ja.add(jo);

    jo = new JSONObject();
    jo.put("id", 2);
    jo.put("key_a", "");
    jo.put("key_b", "val_b");
    ja.add(jo);

    jo = new JSONObject();
    jo.put("id", 3);
    jo.put("key_a", "val_a");
    jo.put("key_b", "val_b");
    ja.add(jo);

    jo = new JSONObject();
    jo.put("id", 4);
    jo.put("key_b", "val_b");
    ja.add(jo);

    jo = new JSONObject();
    jo.put("id", 5);
    jo.put("key_a", "val_a");
    ja.add(jo);

    System.out.println(judgeUsefulData(ja));
    System.out.println(unUsefulDataIdList(ja));
}

private static boolean judgeUsefulData(JSONArray ja){
    return ja.stream().noneMatch(t ->
            !((JSONObject) t).keySet().containsAll(Arrays.asList("key_a", "key_b")) ||
                    StringUtils.isBlank(((JSONObject) t).getString("key_a")) ||
                    StringUtils.isBlank(((JSONObject) t).getString("key_b")));
}

private static List unUsefulDataIdList(JSONArray ja){
    return ja.stream().filter(t ->
            !((JSONObject) t).keySet().containsAll(Arrays.asList("key_a", "key_b")) ||
                    StringUtils.isBlank(((JSONObject) t).getString("key_a")) ||
                    StringUtils.isBlank(((JSONObject) t).getString("key_b")))
            .map(t -> ((JSONObject) t).getInteger("id")).collect(Collectors.toList());
}

console:
false
[1, 2, 4, 5]
  • 将列表转化为Map
public static void main(String[] args) {
    JSONArray ja = new JSONArray();

    JSONObject jo = new JSONObject();
    jo.put("a", "a1");
    jo.put("b", "b1");
    ja.add(jo);

    jo = new JSONObject();
    jo.put("a", "a2");
    jo.put("b", "b2");
    ja.add(jo);

    Map res = ja.stream().collect(
            Collectors.toMap(
                    t -> ((JSONObject) t).getString("a"),
                    v -> ((JSONObject) v).getString("b")
            )
    );
    System.out.println(JSON.toJSONString(res));
}

console:

{"a1":"b1","a2":"b2"}

你可能感兴趣的:(【20005】Java 8 Stream/Collect 使用示例)