Table design
CREATE TABLE 'test' (' id' bigint NOT NULL COMMENT 'id',' name 'varchar(50) COLLATE NOT NULL COMMENT' id', 'next_id' bigint DEFAULT NULL COMMENT 'iD ',);Copy the code
1. Add a record
- Parameter to pass the primary key of the previous dataid, according to theidQuery for this datanext_idRemember toA
- Set the new datanext_id 为 AAnd save,
- Modifies the previous datanext_idIs the primary key of the new dataid
or
- The defaultnext_id 为 – 1Is the newly added data. The sorting is at the end, and the steps of parameter transmission and query are omitted.
(This will not provide the insertion function at the specified location)
2. Modify the sequence
- Parameter passing
- Moved data, before moved, previous dataid (C)
- Moved data, after moved, of the previous dataid (A)
- The data being movedid (D)
- The queryA 的 next_id(remember toB )
- The queryD 的 next_id(remember toE )
- Modify theA 的 next_id 为 DThe primary key of theid
- Modify theD 的 next_id 为 B
- Modify theC 的 next_id 为 E
The idea of moving is as follows
3. Delete
- Parameter pass the id of the previous data, and the ID of the data to be deleted, query the deleted datanext_idRemember toA
- Modifies the previous datanext_id 为 A
- Delete the data to be deleted
Code implementation
1. Simple objects
@Data
public class Tag {
private Integer id;
private String name;
private Integer nextId;
}
Copy the code
2. Sort data by nextId
Public class Test {public static void main(String[] args) {public static void main(String[] args) { 10 -> 40 -> 20 -> 30 -> 50 List<Tag> tags = addData(); // Create a map based on the nextId of each item. Map<Integer, Tag> map = discount.stream ().collect(Collectors. // -1 defaults to the last item: Tag lastTag = map.get(-1); LinkedList<Tag> tagLinkedList = new LinkedList<>(); Get (lasttag.getid (), map, tagLinkedList); tagLinkedList.forEach(System.out::println); } private static void get(int preId, Map<Integer, Tag> map, LinkedList<Tag> tagList) { Tag tag = map.get(preId); if (tag == null) { return; } tagList.addFirst(tag); get(tag.getId(), map, tagList); } private static List<Tag> addData() { List<Tag> tagList = new ArrayList<>(); Tag tag1 = new Tag(); tag1.setId(10); tag1.setName("tag1"); tag1.setNextId(40); tagList.add(tag1); Tag tag4 = new Tag(); tag4.setId(40); tag4.setName("tag4"); tag4.setNextId(20); tagList.add(tag4); Tag tag2 = new Tag(); tag2.setId(20); tag2.setName("tag2"); tag2.setNextId(30); tagList.add(tag2); Tag tag3 = new Tag(); tag3.setId(30); tag3.setName("tag3"); tag3.setNextId(50); tagList.add(tag3); Tag tag5 = new Tag(); tag5.setId(50); tag5.setName("tag5"); tag5.setNextId(-1); tagList.add(tag5); return tagList; }}Copy the code
3. Output the result
Tag(id=10, name=tag1, nextId=40)
Tag(id=40, name=tag4, nextId=20)
Tag(id=20, name=tag2, nextId=30)
Tag(id=30, name=tag3, nextId=50)
Tag(id=50, name=tag5, nextId=-1)
Copy the code