[英]How to convert String to list in java8 using ObjectMapper?
[英]How to return a List of Person instead of String using Java8?
现在,我正在返回一个名称相反的字符串。
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Jamie", 23, Gender.MALE));
personList.add(new Person("Tom", 33, Gender.MALE));
personList.add(new Person("Nancy", 30, Gender.FEMALE));
personList.add(new Person("Michelle", 10, Gender.FEMALE));
System.out.println(reverseWordInList(personList));
}
public static String reverseWords(String sentence) {
return PATTERN.splitAsStream(sentence)
.map(s -> new StringBuilder(s).reverse())
.collect(Collectors.joining(" "));
}
但是,我想要一个新的List<String>
中的反转值怎么做?
您可以直接使用Stream<Person>
中的方法reverseWords
并获取名称颠倒的List<String>
。
List<String> names = personList.stream()
.map(person -> reverseWords(person.getName()))
.collect(Collectors.toList());
因此, reverseWordInList
方法可能如下所示:
具体Person
:
reverseWordInList(personList); ... static List<String> reverseWordInList(List<Person> personList) { return personList.stream().map(person -> reverseWords(person.getName())).collect(Collectors.toList()); }
通用的
reverseWordInList(personList, Person::getName); ... static <T> List<String> reverseWordInList(List<T> list, Function<T, String> getter) { return list.stream().map(t -> reverseWords(getter.apply(t))).collect(Collectors.toList()); }
请注意,这些方法返回一个新列表并且不会修改原始列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.