简体   繁体   English

Java Stream代码改进

[英]Java Stream code improvement

I have a map of cars Map<String, List<Car>> which can be returned by getCarsMap() method where key is model of car , and value is list of cars of same model. 我有一个汽车Map<String, List<Car>>可以通过getCarsMap()方法返回,其中key是汽车的型号,值是同型号汽车的列表。

I would like to improve Car addCar(Car car) function. 我想改进Car addCar(Car car)功能。 For now I wrote this a bit ugly peace of code 现在我写了这个有点难看的代码和平

public Car addCar(Car car) {
    if(getCarsMap().entrySet().stream().anyMatch(es -> es.getKey().equals(car.getModel()))){
        if(!getCarsMap().get(car.getModel()).contains(car)){
            getCarsMap().get(car.getModel()).add(car);
        }
    }else{
        List<Car> tmpList = new ArrayList<Car>();
        tmpList.add(car);
        getCarsMap().put(car.getModel(), tmpList) ;
    }
    return car;
}

Also, need to write something similar for removeCar(Car car) but hope it's gonna be easier with some nice addCar method as a template. 此外,需要为removeCar(Car car)编写类似的东西,但希望用一些漂亮的addCar方法作为模板会更容易。

My idea - rely on compute method of Map. 我的想法 - 依赖于Map的计算方法

So my method populateMapWith process current map according to your case: 所以我的方法根据你的情况populateMapWith进程当前地图:

  • if value list is empty - create new one, add element, add to map 如果值列表为空 - 创建新的,添加元素,添加到地图

  • if present, just add element to current list 如果存在,只需将元素添加到当前列表

as well as removeFromMap according to removing. 以及removeFromMap根据删除。

I illustrated it with Object class, just to simplify the case 我用Object类来说明它,只是为了简化案例

public class BaseTest {

    private Map<String, List<Object>> myMap = new HashMap<>();

    @Test
    public void testName() throws Exception {
        Object car1 = new Object() {
            @Override
            public String toString() {
                return "car1";
            }
        };

        Object car2 = new Object() {
            @Override
            public String toString() {
                return "car1";
            }
        };

        populateMap(car1);
        populateMap(car2);

        assertEquals(2, myMap.get("car1").size());

        removeFromMap(car2);

        assertEquals(1, myMap.get("car1").size());
    }

    private void populateMap(Object o) {
        myMap.computeIfAbsent(o.toString(), key -> new ArrayList<>()).add(o);
    }

    private void removeFromMap(Object o) {
        myMap.computeIfPresent(o.toString(), (key,list) -> { list.remove(o); return list;});
    }
}

UPD : improved methods after discussion with Holger UPD:与Holger讨论后改进的方法

 if(!getCarsMap().get(car.getModel()).contains(car)) 

It seems that you do not wish to have duplicates. 看来你不希望有重复。 So instead of a List, you must use a Set, that does not add duplicate elements, like: 因此,您必须使用不添加重复元素的Set而不是List,例如:

Map<String, Set<Car>> carmap = getCarsMap();

getBoatsMap().put(car.getModel(), tmpList) ;

This doesn't make sense. 这没有意义。 Putting a car in a map that is supposed to have boats is bewildering. 把车放在应该有船的地图上是令人困惑的。 However, I assume to go with it. 但是,我假设顺其自然。

So we can have: 所以我们可以:

Set<Cars> tempcar = new HashSet<>();
tempcar.add(car);
getBoatsMap().put(car.getModel(),tempcar);

public Car addCar(Car car)

The return type of addCar method. addCar方法的返回类型。 A method returns the object that it manipulates. 方法返回它操作的对象。 Here, the map is manipulated and not the object. 这里,操纵地图而不是对象。 It should be something like: 它应该是这样的:

public Map<String,Set<Car>> addCar(Car car)

So we can have the following code: 所以我们可以得到以下代码:

 public HashMap<String,Set<Car>> addCar(Car car){
        Map<String, Set<Car>> carmap = getCarsMap();
        if(carmap.containsKey(car.getModel())){
            HashSet<Car> carset = carmap.get(car.getModel());
            carset.add(car);
            map.put(car.getModel(),carset);
        }else{
            carmap = getBoatsMap();
            Set<Cars> tempcar = new HashSet<>();
            tempcar.add(car);
            carmap.put(car.getModel(),tempcar);
        }
        return carmap;
   }

This can be the basic template for you to move on. 这可以是您继续前进的基本模板。 However, this also can be further optimized. 但是,这也可以进一步优化。 A deeper study of Java Collections API and Java 8 can provide you with better ideas. 对Java Collections API和Java 8的深入研究可以为您提供更好的想法。

For, removeCar(), the method signature can be: 对于removeCar(),方法签名可以是:

public Car removeCar(Car) 

UPDATE I see in comment that getBoatsMap() is a mistake. 更新我在评论中看到getBoatsMap()是一个错误。 So the code is: 所以代码是:

public Map<String, Set<Car>> addCar(Car car){
    Map<String, Set<Car>> carmap = getCarsMap();
    if(carmap.containsKey(car.getModel())){
        HashSet<Car> carset = carmap.get(car.getModel());
        carset.add(car);
        map.put(car.getModel(),carset);
    }else{
        Set<Cars> tempcar = new HashSet<>();
        tempcar.add(car);
        carmap.put(car.getModel(),tempcar);
    }
    return carmap;
}

The tips: 提示:

  • Use Set instead of List because Set doesn't allow duplicates. 使用Set而不是List因为Set不允许重复。

  • Use contains to check if an element is in a collection, regardless of whether it's a List or a Set . 使用contains来检查元素是否在集合中,无论它是List还是Set ( Car class must have a equals method that compares the field values.) Car class必须有一个equals方法来比较字段值。)

  • Return a boolean to indicate if the collection was modified as a result of the operation. 返回一个boolean ,指示集合是否因操作而被修改。 This is what Java collections do. 这就是Java集合所做的事情。

The code: 编码:

public boolean addCar(Car car) {
    Map<String, Set<Car>> carsMap = getCarsMap();
    if (!carsMap.containsKey(car.getModel())) {
        carsMap.put(car.getModel(), new HashSet<>(Arrays.asList(car)));
        return true;
    }
    if (!carsMap.get(car.getModel()).contains(car)) {
        return carsMap.get(car.getModel()).add(car);
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM