我有List
个字符串{1,2,7}
现在我有一个新的List
:{2,4,9}
规则很简单:
所以结果是两个新名单:
删除列表:{1,7}
创建列表:{4,9}
知道如何在java中使其高效吗?也许使用Java8来简化它?
我的列表有大约1000个元素。
答案 0 :(得分:2)
如果排序不重要,请使用Set
批量操作:
Set<String> a = new HashSet<>(Arrays.asList("1", "2", "7"));
Set<String> b = new HashSet<>(Arrays.asList("2", "4", "9"));
Set<String> deleteSet = new HashSet<>(a);
deleteSet.removeAll(b); // [1, 7]
Set<String> createSet = new HashSet<>(b);
createSet.removeAll(a); // [4, 9]
如果你想要Java 8,只需过滤元素并收集:
List<String> deleteList = a.stream().filter(e -> !b.contains(e)).collect(Collectors.toList());
List<String> createList = b.stream().filter(e -> !a.contains(e)).collect(Collectors.toList());
此处,a
和b
可能是列表,但强烈建议将它们Set
设为contains()
,因为在大多数列表实现中{
"@timestamp": "2015-09-22T10:54:35.449+02:00",
"@version": 1,
"HOSTNAME": "server1.example",
"level": "WARN",
"level_value": 30000,
"logger_name": "server1.example.adapter",
"message": "message"
"stack_trace": "ERROR LALALLA\nERROR INFO NANANAN\nSOME MORE ERROR INFO\nBABABABABABBA BABABABA ABABBABAA BABABABAB\n"
}
操作为O(n)
答案 1 :(得分:1)
(function(){
'use strict'
angular.module('app').controller('ChartController', chartController);
chartController.$inject = ['$scope', '$compile'];
function chartController($scope, $compile) {
$scope.getChartElement = function(widgets, i) {
$scope.id = "graphId" + i;
$scope.data = widgets[i]["chart_data"]["data"];
/*var elementString ='<line-graph graph-id="id" graph-data="data" ' + ' width="' + widgets[i]["chart_data"]["divWidth"] + '" height="' + widgets[i]["chart_height"] +
'" colors="' + widgets[i]["chart_data"]["colors"] +
'" interval="' + widgets[i]["chart_data"]["interval"] + '"></line-graph>';*/
var elementString ='<editor ng-model="abc" minlength="3"></editor>';
console.log("Element String : " + elementString);
return elementString;
};
};
})();
基本上我们只创建两个不同的列表。在集合论中,我们可以像这样编写输出:
delete_list = A \ B
create_list = B \ A
感谢@SashaSalauyou关注我犯的错误。
答案 2 :(得分:1)
虽然不是很优雅的解决方案,但我们也可以在Java8中使用AudioContext
:
Streams
打印:
Set<String> setOne = new HashSet<>(Arrays.asList("1","2","7"));
Set<String> setTwo = new HashSet<>(Arrays.asList("2","4","9"));
System.out.println(setOne.stream().filter(i-> !setTwo.contains(i)).collect(Collectors.toList()));
System.out.println(setTwo.stream().filter(i-> !setOne.contains(i)).collect(Collectors.toList()));
重要的一点是[1, 7]
[4, 9]
和setOne
应该有效地最终在lambda表达式中工作。