我有两个类,它们的结构如下:
public class Company {
private List<Person> person;
...
public List<Person> getPerson() {
return person;
}
...
}
public class Person {
private String tag;
...
public String getTag() {
return tag;
}
...
}
基本上,Company类有一个Person对象列表,每个Person对象都可以获得一个标记值。
如果我得到Person对象的列表,是否可以使用Java 8中的Stream找到所有Person对象中最常见的一个标记值(如果是平局,可能只是最常见对象中的一个随机标记值)?
String mostCommonTag;
if(!company.getPerson().isEmpty) {
mostCommonTag = company.getPerson().stream() //How to do this in Stream?
}
发布于 2017-04-26 00:58:24
这对你来说应该是可行的:
private void run() {
List<Person> list = Arrays.asList(() -> "foo", () -> "foo", () -> "foo",
() -> "bar", () -> "bar");
Map<String, Long> commonness = list.stream()
.collect(Collectors.groupingBy(Person::getTag, Collectors.counting()));
Optional<String> mostCommon = commonness.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey);
System.out.println(mostCommon.orElse("no elements in list"));
}
public interface Person {
String getTag();
}
commonness
映射包含找到哪个标签的频率的信息。变量mostCommon
包含最常找到的标记。此外,如果原始列表为空,则mostCommon
为空。
发布于 2017-04-26 01:01:30
您可以将计数收集到地图中,然后获取具有最高值的密钥
List<String> foo = Arrays.asList("a","b","c","d","e","e","e","f","f","f","g");
Map<String, Long> f = foo
.stream()
.collect(Collectors.groupingBy(v -> v, Collectors.counting()));
String maxOccurence =
Collections.max(f.entrySet(), Comparator.comparing(Map.Entry::getValue)).getKey();
System.out.println(maxOccurence);
发布于 2017-04-26 12:46:49
如果您愿意使用第三方库,那么可以使用Eclipse Collections中的Collectors2
和Java8 Stream
来创建一个Bag
并请求topOccurrences
,这将返回一个MutableList
of ObjectIntPair
,它是标记值和出现次数的计数。
MutableList<ObjectIntPair<String>> topOccurrences = company.getPerson()
.stream()
.map(Person::getTag)
.collect(Collectors2.toBag())
.topOccurrences(1);
String mostCommonTag = topOccurrences.getFirst().getOne();
在平局的情况下,MutableList
将有多个结果。
注意:我是Eclipse Collections的提交者。
https://stackoverflow.com/questions/43616422
复制相似问题