madhusudhan
madhusudhan

Reputation: 400

How to Apply if/else logic in stream API in java.?

I have list SortCriteria objects. object contains properties is sortColumn and sortAscending. I need to iterate list if sortAscending is true I need add "ASC" else I need add "DESC"

I have tried get the stream ascending list and stream of descending list and merging.

JSON:

"sort_criteria": [{

      "sortAscending": true,

      "sortColumn": "Category"

}]

JAVA LOGIC:

List<SortCriteria> listOfSortCriteria=webQueryRequest.getSortCriteria();
            List<SortCriteria> listOfAscending=listOfSortCriteria.stream().filter(e->e.getSortAscending().equals("true")).collect(Collectors.toList());
            List<SortCriteria> listOfDescending=listOfSortCriteria.stream().filter(e->e.getSortAscending().equals("false")).collect(Collectors.toList());
            orderByQuery=ORDER_BY+listOfAscending.stream().map(e->e.getSortColumn()+ " "+"ASC").collect(Collectors.joining(","))+","+listOfDescending.stream().map(e->e.getSortColumn()+" "+"DESC").collect(Collectors.joining(","));

Instead of getting the stream ascending list and stream of descending list and merging I want to do at one time need final constructed result.

Upvotes: 0

Views: 116

Answers (1)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

regardless of the original question, order of order columns is significant. by splitting into ascending and descending columns you change the order of order columns!
So, what you need to do is stream the original list and add the columns - each with its own direction:

orderByQuery = ORDER_BY + 
  listOfSortCriteria.stream().map(e->e.getSortColumn() + " " + (e->e.getSortAscending().equals("true") ? "ASC":"DESC"))
    .collect(Collectors.joining(","));

Upvotes: 3

Related Questions