Home > Back-end >  Turn to the List
Turn to the List

Time:01-14

CodePudding user response:

 import Java. Util. *; 
Import the Java. Util. Stream. Collectors;

/* *
* @ author: jiaolian
* @ date: Created in the 2021-01-13 14:04
* @ description: order grouping test
* @ modified By:
* public: call practice
*/
Public class OrderByGroupTest {
Public static void main (String [] args) {

//create order;
List List=new ArrayList ();
List. The add (new Order (" 176 ", 1700));
List. The add (new Order (" 885 ", 4400));
List. The add (new Order (" 885 ", 5100));
List. The add (new Order (" 664 ", 5000));
List. The add (new Order (" 664 ", 2500));
List. The add (new Order (" 481 ", 3000));

//the list according to the oid group
Map ListMap=list. Stream (). Collect (Collectors. GroupingBy (Order: : getOid));

//output test;
Set> The set=listMap. EntrySet ();
Iterator> The iterator=set. The iterator ();
While (iterator. HasNext ()) {
The Map. The Entry Entry=iterator. Next ();
System. The out. Println (" is the key: "+ entry. GetKey () +" val: "+ entry. GetValue ());
}


}

//TODO simplified order object
Private static class Order {
//order id
Private String oid;
//price
Private double price;

Public Order (String oid, double price) {
Enclosing the oid=oid;
This. Price=price;
}

Public String getOid () {
Return the oid.
}

Public void setOid (String oid) {
Enclosing the oid=oid;
}

Public double getPrice () {
The return price;
}

Public void setPrice (double price) {
This. Price=price;
}

@ Override
Public String toString () {
Return the Order {" + "
"The oid='" + oid +' \ ' '+
"Price=" + price +
'} ';
}
}
}


Simplifies the orders table Order, the code used JDK1.8 new feature List fluidization, one line of code that can be done to the List grouping, 1.8 before need by Order id group into the List, and then put the List into the Map, below is the test result, if it works for you, please give a attention!

CodePudding user response:

Group by your id, put all the id is found out, and then loop through to go out and out is not the same?
  • Related