How to filter this using streams or any other way to write in one line instead of for-loop.
class Attribute {
String name;
String value;
..
//getter-setter
}
.. main
List<Attribute> list = populateAttributes();
for (Attribute attr : list) {
if (attr.name == "some key") {
return attr.value;
}
}
I am interested to do so in 1 line since I will be reading that path from config and my generic code will traverse the dot sequence and invoke methods using reflection. So something like this classpackage.getAttributes...(getValue where attr.getname == "somekey")
You can use Stream.filter() to filter the list with attributes whose attribute name matches your key and find the first attribute:
Optional<Attribute> attributeOptional = list.stream().filter(attr-> "some key".equals(attr.name).findFirst();
Edit: if you want the value out of the attribute then you can use Optional.map() to map found attribute to its value, and if's not found then some default value like null.
String value = list
.stream()
.filter(attr-> key.equals(attr.name))
.findFirst()
.map(attribute -> attribute.value)
.orElse(null);