I have the following ArrayLists: 1) List<MAP<String,String>>
in 2) ArrayList<>()
:
[
[{name=a,age=33,city=NY},{name=b,age=23,city=NY},{name=d,age=83,city=CA}],
[{name=f,age=53,city=FL}],
[{name=d,age=11,city=TX},{name=a,age=13,city=CA}],
]
I want to get new ArrayList with distinct values of names as:
[{a},{b},{d},{f}]
Can you assist :)?
You can Iterate through your collection and add it to a Hash set to get Unique names.
List<Map<String,String>> input = new ArrayList<>();
Set <String> uniqueNames = new HashSet<>();
for( Map<String, String> stringStringMap : input )
uniqueNames.add(stringStringMap.get("name"));
Or In Java8 this can be done in one line using stream
Set<String> uniqueNames = input.stream().map(a -> a.get("name")).collect(Collectors.toSet());
And then you can use set to create an ArrayList(as you mentioned ArrayList in question ).
Using Java 8 you can do
//List<Map<String, String>> inList = new ArrayList<>();
List<String> outList = inList.stream().map(m -> m.get("name")).distinct().collect(Collectors.toList());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.