jdk8-stream的使用

/**
 * 
 */
package com.gewb.stream;

/**
 * @author Bingo.Ge
 * @date 2020年6月15日
 */
public class Dish {
	private final String name;
	private final boolean vegetarian;
	private final int calories;
	private final Type type;
	
	
	/**
	 * @param name
	 * @param vegetarian
	 * @param calories
	 * @param type
	 */
	public Dish(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};
	
	
	
}
/**
 * 
 */
package com.gewb.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Bingo.Ge
 * @date 2020年6月15日
 */
public class SimpleStream {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List<Dish> menu = Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
										new Dish("beef", false, 700, Dish.Type.MEAT),
										new Dish("chicken", false, 400, Dish.Type.MEAT),
										new Dish("french fries", true, 530, Dish.Type.OTHER),
										new Dish("rice", true, 350, Dish.Type.OTHER),
										new Dish("season fruit", true, 120, Dish.Type.OTHER),
										new Dish("pizza", true, 550, Dish.Type.FISH),
										new Dish("prawns", false, 300, Dish.Type.FISH),
										new Dish("salmon", false, 450, Dish.Type.FISH));
		
		List<String> dishNamesByCollections = getDishNameByCollection(menu);
		System.out.println(dishNamesByCollections);
		
		List<String> dishNamesByStream = getDishNameByStream(menu);
		System.out.println(dishNamesByStream);

	}

	/**
	 * @param menu
	 * @return
	 */
	private static List<String> getDishNameByStream(List<Dish> menu) {
		List<String> collect = menu.stream().filter(o -> o.getCalories() <= 400)
						.sorted(Comparator.comparing(Dish::getCalories))
						.map(Dish :: getName)
						.collect(Collectors.toList());
		return collect;
	}

	/**
	 * @param menu
	 * @return
	 */
	private static List<String> getDishNameByCollection(List<Dish> menu) {
		Collections.sort(menu, new Comparator<Dish>() {
			@Override
			public int compare(Dish o1, Dish o2) {
				return Integer.compare(o1.getCalories(), o2.getCalories());
			}
		});
		
		List<String> dishNameList = new ArrayList<>();
		for (Dish dish : menu) {
			if(dish.getCalories() <= 400) {
				dishNameList.add(dish.getName());
			}
		}
		
		return dishNameList;
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章