Как отсортировать Arraylist, чтобы его коллекция была отсортирована по списку значений - PullRequest
0 голосов
/ 04 мая 2020

У меня есть Arraylist , который содержит рецепты, и каждый рецепт содержит список ингредиентов. Получатели отображаются в списке пользовательского интерфейса приложения Android, и пользователи хотят отсортировать список по ингредиентам, которые им нравятся больше всего.

Например, это список ингредиентов, которые им нравятся больше всего

1 - Cheese
2 - Potato
3 - Tuna
4 - Chicken

Итак, в списке получателей сначала должны быть показаны все ингредиенты, содержащие сыр, а затем картофель и т. Д. c. Как мне заархивировать это с помощью java stream()?

Вот как мои классы моделей сейчас

public class Recipe {

    String[] ingredients;
    private String description;
    private String title;


    public String[] getIngredients() {
        return ingredients;
    }

    public void setIngredients(String[] ingredients) {
        this.ingredients = ingredients;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

.

public class Ingredient {

    String title;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

Ответы [ 2 ]

1 голос
/ 05 мая 2020

Ваш класс Recipe не использует ваш класс Recipe, поэтому ваша модель может быть изменена для использования класса Ingredient.

public class Recipe {
    List<Ingredient> ingredients;
    ...
}

Вы можете создать свой собственный компаратор для сортировки, если в рецепте есть какой-либо ингредиент.

public class ContainsIngredientComparator implements Comparator<Recipe> {

    private Ingredient ingredient;

    public ContainsIngredientComparator(Ingredient ingredient) {
        this.ingredient = ingredient;
    }   

    @Override
    public int compare(Recipe r1, Recipe r2) {
        if (r1.getIngredients().contains(ingredient)) {
            if (r2.getIngredients().contains(ingredient)) {
                return 0;
            } else {
                return -1;
            }
        } else if (r2.getIngredients().contains(ingredient)) {
            return 1;
        } else {
            return 0;
        }
    }
}

Теперь вы можете создать компаратор для каждого ингредиента и связать все компараторы. Вы можете использовать Stream API для сопоставления избранных ингредиентов с компараторами и использовать thenComparing для связывания компараторов:

Optional<ContainsIngredientComparator> favoritesComparator = favorites.stream()
        .map(ContainsIngredientComparator::new)
        .reduce((c1, c2) -> (ContainsIngredientComparator) c1.thenComparing(c2));

Вы можете использовать результат Comparator для сортировки списка:

List<Recipe> recipeList = // ... get the recipeList
if (favoritesComparator.isPresent()) {
    recipeList.sort(favoritesComparator.get());
}
1 голос
/ 05 мая 2020

Вы можете создать компаратор Картофель и Компаратор Сыр, а затем отсортировать на их основе

  static class Recipie {
        List<String> list;

        public Recipie(List<String> list) {
            this.list = list;
        }

        @Override
        public String toString() {
            return list.toString();
        }
    }

    public static void main(String[] args) {
               List<Recipie> recipies = new ArrayList<>();
        recipies.add(new Recipie(Arrays.asList("Cheese", "Potato", "Onions")));
        recipies.add(new Recipie(Arrays.asList("Tuna", "Potato", "Chicken")));
        recipies.add(new Recipie(Arrays.asList("Potato", "Cheese")));
        recipies.add(new Recipie(Arrays.asList("Chicken")));
        recipies.add(new Recipie(Arrays.asList("Chicken", "Potato")));
        recipies.add(new Recipie(Arrays.asList("Cheese", "Tomato")));

        List<Recipie> result = recipies.stream().sorted(Comparator.comparing(r -> !r.list.contains("Potato")))
                .sorted(Comparator.comparing(r -> !r.list.contains("Cheese"))).collect(Collectors.toList());

        System.out.println(result);
    }

, на выходе

[[Cheese, Potato, Onions], [Potato, Cheese], [Cheese, Tomato], [Tuna, Potato, Chicken], [Chicken, Potato], [Chicken]]
...