JDK8之Collectors之Joining

public class CollectorsTest03 {

public static void main(String[] args) {

List<TestDemo> menu = Arrays.asList(
new TestDemo("pork", false, 800, TestDemo.Type.MEAT),
new TestDemo("beef", false, 700, TestDemo.Type.MEAT),
new TestDemo("chicken", false, 400, TestDemo.Type.MEAT),
new TestDemo("french fries", true, 530, TestDemo.Type.OTHER),
new TestDemo("rice", true, 350, TestDemo.Type.OTHER),
new TestDemo("season fruit", true, 120, TestDemo.Type.OTHER),
new TestDemo("pizza", true, 550, TestDemo.Type.OTHER),
new TestDemo("prawns", false, 300, TestDemo.Type.FISH),
new TestDemo("salmon", false, 450, TestDemo.Type.FISH));

//1、join
Optional.ofNullable(menu.stream().map(TestDemo::getName).collect(Collectors.joining(","))).ifPresent(System.out::println);
Optional.ofNullable(menu.stream().map(TestDemo::getName).collect(Collectors.joining(",","NAME:[","]"))).ifPresent(System.out::println);

Optional.ofNullable(menu.stream().collect(Collectors.mapping(TestDemo::getName,Collectors.joining(",")))).ifPresent(System.out::println);

//输出结果:

// pork,beef,chicken,french fries,rice,season fruit,pizza,prawns,salmon
// NAME:[pork,beef,chicken,french fries,rice,season fruit,pizza,prawns,salmon]
// pork,beef,chicken,french fries,rice,season fruit,pizza,prawns,salmon


}

static class TestDemo {
private String name;
private boolean vegetarian;
private int calories;
private Type type;

public TestDemo(String name, boolean vegetarian, int calories, Type type) {
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
this.type = type;
}

public String getName() {
return name;
}

public boolean isVegetarian() {
return vegetarian;
}

public int getCalories() {
return calories;
}

public Type getType() {
return type;
}

public enum Type {MEAT, FISH, OTHER}


@Override
public String toString() {
return "TestDemo{" +
"name='" + name + '\'' +
", vegetarian=" + vegetarian +
", calories=" + calories +
", type=" + type +
'}';
}
}

}
posted @ 2022-01-06 15:48  java_my_skill  阅读(144)  评论(0)    收藏  举报