Java 8 потоков поддерживают спецификацию c порядок отображения ключей карты из группы по операции - PullRequest
2 голосов
/ 26 апреля 2020

У меня есть список с коллекциями объектов TitleIsbnBean. Я написал следующий фрагмент кода для группировки по этой коллекции по типу области обучения, как показано ниже.

titleListByLearningArea = nonPackageIsbnList.stream()
      .collect(groupingBy(TitleIsbnBean::getKeylearningarea,
                          LinkedHashMap::new,Collectors.toList())

              );

, но я хочу сохранить следующий указанный порядок c в карте, возвращаемой из указанного выше потока.

titleListByLearningArea.put("Commerce", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("English", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Health & PE", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Humanities", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Mathematics", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Music & the Arts", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Science", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Others", new ArrayList<TitleIsbnBean>() {});

но я получаю другой порядок, когда группирую коллекции по потокам. Как я могу поддерживать определенный c порядок, когда группа потоков по операциям использует.

class TitleIsbnBean {

  private String titleName;
  private String isbn;
  private int status;
  private String keylearningarea;

  public TitleIsbnBean(String titleName, String isbn, int status, String keylearningarea){
    super();
    this.titleName = titleName;
    this.isbn = isbn;
    this.status = status;
    this.setKeylearningarea(keylearningarea);
  }

}

ArrayList<TitleIsbnBean> nonPackageIsbnList = new ArrayList<>();
Map<String,List<TitleIsbnBean>> titleListByLearningArea = new LinkedHashMap<>();

titleListByLearningArea.put("Commerce", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("English", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Health & PE", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Humanities", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Mathematics", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Music & the Arts", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Science", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Others", new ArrayList<TitleIsbnBean>() {});

titleListByLearningArea = nonPackageIsbnList.stream()
.collect(Collectors.groupingBy(TitleIsbnBean::getKeylearningarea,
                                LinkedHashMap::new,Collectors.toList()));

Ответы [ 2 ]

4 голосов
/ 26 апреля 2020

Учитывая, что вам необходим желаемый порядок ключей для Map, который вы собираете, вы можете получить до TreeMap с Comparator на основе указанного index, например:

Collection<TitleIsbnBean> nonPackageIsbnList = .... //initialisation
List<String> orderedKeys = List.of("Commerce", "English", "Health & PE", "Humanities",
        "Mathematics", "Music & the Arts", "Science", "Others");

Map<String, List<TitleIsbnBean>> titleListByLearningArea = nonPackageIsbnList.stream()
        .collect(Collectors.groupingBy(TitleIsbnBean::getKeylearningarea,
                () -> new TreeMap<>(Comparator.comparingInt(orderedKeys::indexOf)),
                Collectors.toList()));
2 голосов
/ 26 апреля 2020

Сначала отсортируйте список, используя Comparator с нужным вам порядком, затем соберите список в группу.

List<String> orderKeys = List.of("Commerce", "English", "Health & PE", "Humanities",
        "Mathematics", "Music & the Arts", "Science", "Others");

Map<String, List<TitleIsbnBean>> titleListByLearningArea = nonPackageIsbnList.stream()
                   .sorted(Comparator.comparingInt(t -> orderKeys.indexOf(t.getKeylearningarea())))
                   .collect(Collectors.groupingBy(TitleIsbnBean::getKeylearningarea,LinkedHashMap::new,Collectors.toList()));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...