Sort Java stream as conditional conditional

I am trying to sort a stream in a specific order with one of its fields.

Now I achieve this by converting the streams to a list and using the switch, and then attaching them to the list in the desired order.

    fruits.forEach (fruit -> {
                switch (fruit.getName ()) {
                    case "Orange":
                        orangesList.add (fruit);
                        break;
                    case "Apple":
                        applesList.add (fruit);
                        break;
                    case "WaterMelon":
                        watermelonList.add (fruit);
                        break;
                    default:
                        otherFruits.add (fruit);
                        break;
                }
    });

    genericFruitList.addAll (0, orangeList);
    genericFruitList.addAll (1, applesList);
    genericFruitList.addAll (2, watermelonList);
    genericFruitList.addAll (3, otherFruits);

I wonder if there are any changes to achieve this using a stream-sorted method and using a custom comparator or something like that.

Thanks in advance.

+4
source share
2 answers

You can create a comparator using an explicit order, e.g.

List<String> order = Arrays.asList("Orange", "Apple", "WaterMelon");
Comparator<String> comp
    = Comparator.comparingInt(name -> order.indexOf(name)-Integer.MIN_VALUE);

which can be used as

List<Fruit> genericFruitList = fruits
    .sorted(Comparator.comparing(fruit -> fruit.getName(), comp))
    .collect(Collectors.toList());

however, sorting the entire list, especially using the comparator List.indexOf, can be inefficient. An alternative would be

List<Fruit> genericFruitList = fruits
    .collect(Collectors.groupingBy(fruit -> fruit.getName()))
    .entrySet().stream()
    .sorted(Map.Entry.comparingByKey(comp))
    .flatMap(e -> e.getValue().stream())
    .collect(Collectors.toList());

Fruit .

Bucket Sort.

+6

( , , , "" ), :

List<String> order = Arrays.asList("Orange", "Apple", "Watermelon");
Comparator<Fruit> comparator = Comparator.comparing(f -> {
  int i = order.indexOf(f.getName());
  return (i >= 0) ? i : order.size();
});

:

List<Fruit> genericFruitList = fruits.stream().sorted(comparator).collect(Collectors.toList());
+5

Source: https://habr.com/ru/post/1685302/


All Articles