我得到了像
这样的表格List<List<Integer>> table = new ArrayList<>()
其中List是表行,我需要将所有重复值ALL OVER THE TABLE设置为null,如何才能通过ArrayList&amp;&amp; foreach循环|| λ - 表达式?
必须以某种方式工作:
1 2 3 null 2 3
4 1 5 -> 4 null 5
1 6 9 null 6 9
抱歉我的英语不好,谢谢你的快速反应!
答案 0 :(得分:2)
使用java-8,
//Find duplicates
Map<Integer, Long> counts =
table.stream()
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(i->i, Collectors.counting()));
// and remove them
table.stream().forEach(row -> row.replaceAll(i-> counts.get(i) > 1 ? null : i));
答案 1 :(得分:0)
将(稍微不清楚)问题解释为重复数据删除(删除而不是“归零”):
List<List<Integer>> dedup = table.stream().distinct().collect(toList());
或java 7:
List<List<Integer>> dedup = new ArrayList<>(new LinkedHashSet<>(table));
通常更有用。
但是,如果归零确实需要:
Set<List<Integer>> set = new HashSet<>();
List<List<Integer>> dedup = table.stream()
.filter(list -> set.add(list) ? list : null)
.collect(toList());
Set的add()
方法返回true
正在添加更改集合的元素 - 即它是否是之前未见过的元素。
答案 2 :(得分:0)
试试这个,这种方法是为List
中存在的所有元素构建索引图,如果为键找到多个值,则将值设置为null
List<List<Integer>> table = new ArrayList<>();
table.add(Arrays.asList(1, 2, 3));
table.add(Arrays.asList(4, 1, 5));
table.add(Arrays.asList(1, 6, 9));
System.out.println("Before " + table);
Map<Integer, List<List<Integer>>> indices = new HashMap<>();
for (int i = 0; i < table.size(); i++) {
for (int j = 0; j < table.get(i).size(); j++) {
int el = table.get(i).get(j);
if (indices.get(el) == null) {
indices.put(el, new ArrayList<>());
}
indices.get(el).add(Arrays.asList(i, j));
}
}
indices.keySet().stream()
.filter(k -> indices.get(k).size() > 1)
.flatMap(k -> indices.get(k).stream())
.forEach(li -> table.get(li.get(0)).set(li.get(1), null));
System.out.println("After " + table);
输出
Before [[1, 2, 3], [4, 1, 5], [1, 6, 9]]
After [[null, 2, 3], [4, null, 5], [null, 6, 9]]