Listlist1 = Arrays.asList("apple", "banana", "cherry", "apple"); Map map1 = list1.stream().collect(Collectors.toMap(Function.identity(), String::length)); System.out.println(map1);
ListIn this example, we have a list of Person objects and we use the toMap method to collect them into a Map where the name is the key and the age is the value. Both of these examples use the Collectors class from the java.util.stream package library.personList = Arrays.asList(new Person("John", 30), new Person("Jane", 25), new Person("Jack", 40)); Map map2 = personList.stream().collect(Collectors.toMap(Person::getName, Person::getAge)); System.out.println(map2);