Get the App
SLTechnology News&Howtos  ›  Development  › 

How to operate and transfer List and Map by JDK8 through Stream

Shulou Source: shulou.com Published: 2022-06-03 20:02:14 10月27日 Update

This article mainly explains "how JDK8 operates and converts List and Map through Stream". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how JDK8 operates and converts List and Map through Stream."

1. Convert the Map data into the List of the custom object, for example, the key,value of map corresponds to two attributes of the Person object:

List list = map.entrySet (). Stream (). Sorted (Comparator.comparing (e-> e.getKey () .map (e-> new Person (e.getKey (), e.getValue () .map (Collectors.toList ()); List list = map.entrySet (). Stream (). Sorted (Comparator.comparing (Map.Entry::getValue)) .map (e-> new Person (e.getKey (), e.getValue () .map (Collectors.toList ()) List list = map.entrySet () .stream () .sorted (Map.Entry.comparingByKey ()) .map (e-> new Person (e.getKey (), e.getValue () .duration (Collectors.toList ())

The difference between the above three ways lies in the processing of sorting. Reference link:

Https://www.concretepage.com/java/jdk-8/java-8-convert-map-to-list-using-collectors-tolist-example

2. Convert List objects to other List objects:

List employees = persons.stream () .filter (p-> p.getLastName () .filter ("L1")) .map (p-> new Employee (p.getName (), p.getLastName (), 1000)) .filter (Collectors.toList ())

3. Filter out an element from the List

User match = users.stream () .filter ((user)-> user.getId () = = 1) .findAny () .get ()

4. Convert List to Map

Public class Hosting {private int Id; private String name; private long websites; public Hosting (int id, String name, long websites) {Id = id; this.name = name; this.websites = websites;} / / getters, setters and toString ()} Map result1 = list.stream () .collect (Collectors.toMap (Hosting::getId, Hosting::getName))

At this point, I believe you have a deeper understanding of "JDK8 how to List, Map operation and interconversion through Stream". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Objects content learning different practical deeper two elements interests practicality practicality attributes simple operation data methods methods more friends websites links Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker macOS vpn Shulou Tech Info NVidia